目标C问题与圆形浮动 [英] Objective C Issue With Rounding Float

查看:89
本文介绍了目标C问题与圆形浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,将计算结果舍入到两位小数。



这是一个财务计算,当结果涉及到一分钱时,我期望这个数字被四舍五入,但实际上正在向下舍入。



要复制问题:

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

返回:

 code>所有DP:16.695000 
2 DP:16.69

而我期望看到:

 全部DP:16.695000 
2 DP:16.70
任何人都可以建议,如果这是设计,或者(很可能)我错过了一些东西,如果有什么我可以做的来绕过它。在这种情况下,它是重要的。



提前感谢
Oli

解决方案

不要使用 float 用于财务计算!



有浮点值 不能正好代表 16.695 是其中之一。当您尝试将该值存储在浮点数中时,您实际获得最接近的可表示值。当您对浮动执行一系列操作时,可能会失去精度,而那么你失去准确性。这导致损失。



使用实际的货币类型,使用 NSDecimalNumber ,或者使用 int 进行所有的计算,它计算最小的单位关心(即, 1050 是$ 10.50美分,或$ 1.050如果你想要几分钱)。


I have an issue with rounding the result of a calculation to two decimal places.

It is a financial calculation and when the result involves half a penny I would expect the number to be rounded up but it is in fact being rounded down.

To replicate the issue:

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

Returns:

All DP: 16.695000
2 DP: 16.69

Whereas 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 anything I can do to get around it. It is vital that it rounds up in this scenario.

Thanks in advance, Oli

解决方案

Don't use floats for financial calculations!

There are values that floats cannot represent exactly. 16.695 is one of them. When you try to store that value in a float, you actually get the closest representable value. When you perform a series of operations on a float, you can lose precision, and then you lose accuracy. This leads to losing money.

Use an actual currency type, use NSDecimalNumber, or do all your calculations with ints that count the smallest unit you care about (i.e., 1050 is $10.50 in whole cents, or $1.050 if you want fractions of pennies).

这篇关于目标C问题与圆形浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆