Objective C Issue With Rounding Float

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-17 16:39:42

问题


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


回答1:


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).




回答2:


As far as I am aware the NSLog() function only takes formatting arguments and makes no attempt to round.

You may be use to using a printf() style function that does support rounding.

I suggest using one of the many functions in math.h to round your value before output and only rely on NSLog() for formatting.




回答3:


After seeing the comments

Use the C standard function family round(). roundf() for float, round() for double, and roundl() for long double. You can then cast the result to the integer type of your choice




回答4:


you could try this:

 - (void)testNSlogMethod {

    float value = 16.695; //--16.70
    value = value *100;

    int mulitpler = round(value);

    NSLog(@"%.2f",mulitpler/100.0f);
}


来源:https://stackoverflow.com/questions/6333711/objective-c-issue-with-rounding-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!