Task C Float Rounding Problem

I have a problem with rounding the calculation result to two decimal places.

This is a financial calculation, and when the result includes half a penny, I expect the number to be rounded, but in fact it is rounded.

To reproduce the problem:

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

Returns:

All DP: 16.695000
2 DP: 16.69

While 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 something that I can do to get around it. It is very important that it is rounded in this scenario.

Thanks in advance, Oli

+3
source share
4 answers

Do not use floatfor financial calculations!

, . 16.695 . , . , , . .

, NSDecimalNumber int, , about (.. 1050 10,50 , $1,050, ).

+8

, NSLog() .

printf(), .

math.h NSLog() .

+3

Use the C round () family of standard functions . roundf () for float, round () for double, and roundl () for long double >. Then you can apply the result to the integer type of your choice.

0
source

you can try the following:

 - (void)testNSlogMethod {

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

    int mulitpler = round(value);

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

All Articles