Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C Issue With Rounding Float

I have an issue with rounding the result of a calculation to two decimal places.

It is a financial calculation and when the result involves half a penny I would expect the number to be rounded up but it is in fact being rounded down.

To replicate the issue:

float raw = 16.695;
NSLog(@"All DP: %f",raw);
NSLog(@"2 DP: %.2f",raw);

Returns:

All DP: 16.695000
2 DP: 16.69

Whereas I would expect to see:

All DP: 16.695000
2 DP: 16.70

Can anyone advise if this is by design or if (most likely) I am missing something and if there is anything I can do to get around it. It is vital that it rounds up in this scenario.

Thanks in advance, Oli

like image 660
faroligo Avatar asked Dec 29 '25 02:12

faroligo


1 Answers

Don't use floats for financial calculations!

There are values that floats cannot represent exactly. 16.695 is one of them. When you try to store that value in a float, you actually get the closest representable value. When you perform a series of operations on a float, you can lose precision, and then you lose accuracy. This leads to losing money.

Use an actual currency type, use NSDecimalNumber, or do all your calculations with ints that count the smallest unit you care about (i.e., 1050 is $10.50 in whole cents, or $1.050 if you want fractions of pennies).

like image 84
jscs Avatar answered Dec 31 '25 16:12

jscs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!