Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: floorf( ) returns wrong value

Here is the code:

    float passedPrice = 2.953;
    float placed = 1000.0; //3 decimals
    NSLog("%f", placed); // Gives 2953;
    float withNoFractions = floorf(passedPrice * placed);

The value stored in withNoFractions is 2952! It shall be 2953. What is really strange is that it works some time.

like image 734
Abdalrahman Shatou Avatar asked Dec 08 '25 23:12

Abdalrahman Shatou


1 Answers

Many decimal floating point fractions cannot be represented as exact fractions in binary, so they have to be approximated. 2.953 is being approximated as something like 2.95299999. When you multiply by 1000, the result is 2952.99999, and when you get the floor of this, it's 2952.

To solve this, you can either use round() instead of ffloorf(), or you can add 0.5 before calling ffloorf():

float withNoFractions = floorf(passedPrice * placed + 0.5);
like image 72
Barmar Avatar answered Dec 10 '25 16:12

Barmar



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!