[英]Objective C Issue With Rounding Float
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在此先感谢,奥利
float
s for financial calculations! float
进行财务计算! There are values that floats cannot represent exactly .浮点数无法准确表示某些值。
16.695
is one of them. 16.695
就是其中之一。 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 int
s that count the smallest unit you care about (ie, 1050
is $10.50 in whole cents, or $1.050 if you want fractions of pennies).使用实际的货币类型,使用NSDecimalNumber ,或者使用
int
进行所有计算,计算您关心的最小单位(即, 1050
是 10.50 美元的整美分,或者 1.050 美元,如果你想要几分之一便士)。
As far as I am aware the NSLog()
function only takes formatting arguments and makes no attempt to round.据我所知,
NSLog()
function 只需要格式化 arguments 并且不尝试舍入。
You may be use to using a printf()
style function that does support rounding.您可能习惯于使用支持舍入的
printf()
样式 function。
I suggest using one of the many functions in math.h
to round your value before output and only rely on NSLog()
for formatting.我建议使用
math.h
中的众多函数之一在 output 之前对您的值进行四舍五入,并且仅依靠NSLog()
进行格式化。
After seeing the comments看到评论后
Use the C standard function family round().使用 C 标准 function 系列圆形()。 roundf() for float, round() for double, and roundl() for long double .
roundf()用于浮点,round()用于双精度, roundl()用于长双精度。 You can then cast the result to the integer type of your choice
然后,您可以将结果转换为您选择的 integer 类型
you could try this:你可以试试这个:
- (void)testNSlogMethod {
float value = 16.695; //--16.70
value = value *100;
int mulitpler = round(value);
NSLog(@"%.2f",mulitpler/100.0f);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.