Objective-C: floorf( ) returns wrong value

喜夏-厌秋 提交于 2019-12-08 00:39:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/17158903/objective-c-floorf-returns-wrong-value

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