我的应用程序是这样计算的。
float containTaxValue = 840;
float taxRate = 5;
float divisionedNum = (100 + taxRate)/100;
float removedTaxValue = containTaxValue/divisionedNum;
float taxValue = containTaxValue - removedTaxValue;
最后的答案是
NSLog(@"%f",removedTaxValue); => 800.000061
NSLog(@"%f",containTaxValue); => 840.000000
NSLog(@"%f",taxValue); => 39.999939
我想在这段代码中得到“taxValue == 40.000000”。
我无法理解问题出在哪里。请让我知道任何建议。
最佳答案
IEEE 754 标准是一种以易于机器操作的方式存储 float 的方法。该方法被处理器的 INTel 和 mot 使用。
IEEE 754 指定数字以二进制格式存储以减少存储要求,并允许所有微处理器上可用的内置二进制算术指令以相对快速的方式处理数据。然而,一些简单的、不重复的十进制数被转换为重复的二进制数,无法以完美的精度存储。
1/10可以用十进制表示.1
但在二进制形式中它变成了: .0001100011000111000111(等等)
And Hence the rounding-off error occurs.
您必须将其转换为 int
才能四舍五入。
1.05的二进制转换也进行 00111111 10000110 01100110 01100110....
关于ios - Objective-C 中计算 float 的奇怪值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15472470/