objective-c - 对 c/objective-c 中的 float 进行舍入。最后一位数字为 5 时出错

标签 objective-c c cocoa-touch floating-point currency

简化的问题:

我有一个 float 0.02275,当我将其四舍五入到小数点后 4 位时,我得到的是 0.0227,而不是预期的 0.0228。我知道发生这种情况是因为 0.02275 的浮点值类似于 0.0227499999999999...,四舍五入到小数点后 4 位后得到 0.0227

float a = 0.02275;
NSLog(@"float a is %f",a);
NSLog(@"float a, rounded to 4 decimal places is %0.4f",a);
NSLog(@"float a, rounded to 10 decimal places is %0.10f",a);

给出输出

float a is 0.022750
float a, rounded to 4 decimal places is 0.0227
float a, rounded to 10 decimal places is 0.0227499995

我的问题是:如何正确舍入此值以获得 0.0228 而不是 0.0227

真实情况的局限性:

float 取自plist文件; NSNumber floatValue 在将其分配给变量 a 时使用。

我的程序正在处理金钱和百分比。货币值是用户输入的,百分比要么是固定的,要么是用户输入的。上例中的 float 是导致我的计算不准确的百分比值之一。

最佳答案

不要使用 float 来存储货币值。错误会不断增加,这对于金钱来说通常是不可取的。将钱以整数形式存储为美分(如果可以有小数美分金额,则为十分之一美分......)。还将百分比存储为整数,例如 100%=1000 或您想要的任何精度。

示例:

$10 * 105% (logical)
= 1000 * 1050 (variable values)
= 1050000 (intermediate result)
/ 1000 (divide by numeric value of 100%)
= 1050 (final cent value)
= (double)1050/100.0 (C code to get dollars as double for printing)

关于objective-c - 对 c/objective-c 中的 float 进行舍入。最后一位数字为 5 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994572/

相关文章:

ios - iphone sdk可以录制mp3吗?

ios - itunes 商店操作失败错误说明不可用

c - float 据类型不确定

c - 如何切换字符串大小写?

iphone - 使用 UIImagePickerController 实现放大/缩小

ios - 模拟器是否播放视频?

ios - 将对象存储到 NSMutableArray

iphone - 如何调整 UIToolBar 左右内边距

iphone - 当没有要删除的单元格时,如何关闭 UITableView 中的编辑模式?

自定义工具提示格式