Trouble with floats getting rounded up

This one is making me scratch my head.

Here’s what I have:

Current = 123456.78f;
Money = Current.ToString("F2");
print("c: "+Current+" m: "+Money);

The output is:
c: 123456.8 m: ‘123456.80’

Why is this number getting rounded up? I’m not doing ANYTHING to round it. I want both digits past the decimal point, exactly as they are. Help!

I think it’s just floating point precision. If you just do this:

float f = 123456.78f
Debug.Log(f); 

It also just outputs 123456.8.

If you want better precision, use double.

For money, which needs to be exact, use integers / fixed point arithmetic, the last two digits being cents. For example, 123456.78 as an integer would simply be 12345678.

2 Likes

Decimal datatype is used for currency

1 Like