为什么在格式化数字时 NSString 类舍入不一致? [英] Why does the NSString class round inconsistently when formatting numbers?

查看:75
本文介绍了为什么在格式化数字时 NSString 类舍入不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两行的输出似乎表明 NSString 的 stringWithFormat 语句没有一致地舍入数字.它似乎正确地从 0.75 向上取整到 0.8.但它将 0.25 舍入到 0.2.这是代码.

The output of the following two lines seem to show that NSString's stringWithFormat statement does not round numbers consistently. It seems to round up correctly from 0.75 to 0.8. But it rounds 0.25 down to 0.2. Here is the code.

    NSString *sRoundedScore = [NSString stringWithFormat:@"%.1f", fScore];
    NSLog(@"\r\n score before rounding: %f, rounded score: %@", fScore, sRoundedScore);

当 fScore 指定为 0.25 时,输出为:

When fScore is assigned to be 0.25, the output is:

score before rounding: 0.250000, rounded score: 0.2

当 fScore 指定为 0.75 时,输出为:

When fScore is assigned to be 0.75, the output is:

score before rounding: 0.750000, rounded score: 0.8

我不得不开始使用 NSNumberFormatter 来获得一致的结果.为什么 stringWithFormat 会在结果中产生这种变化?

I had to begin using NSNumberFormatter to get this to round consistently up. Why though does stringWithFormat produce this variation in results?

推荐答案

这个答案可以追溯到printf"功能

This answer goes back to "printf" functionality

银行家四舍五入:

重要的是要知道这更说明您想在浮点整数上显示一位小数.

It's important to know this is more stating that you want to show one decimal place on a Floating point integer.

由于您指定了一位小数点,因此正在检查小数点后的第二位来决定四舍五入的位置.%.f 格式化程序的四舍五入逻辑是这样工作的:如果您前面的数字小于 4,那么如果您前面的数字是 4 并且大于 5,则向下四舍五入.

Since you are stating one decimal point it is examing the second decimal to decide where to round. The rounding logic for %.f format'er works like so: if your number directly ahead is under 4 then 5 rounds down if you your number directly ahead is 4 and above 5 rounds up.

原因:http://linuxgazette.net/144/misc/lg/a_question_of_rounding_in_issue_143.html:对于 GNU C 库,printf() 使用的舍入规则是银行家舍入"或舍入到偶数".这比其他一些 C 库更正确,因为 C99 规范说转换为十进制应该使用当前选定的 IEEE 舍入模式(默认银行家舍入)."

Reason of this: http://linuxgazette.net/144/misc/lg/a_question_of_rounding_in_issue_143.html: "For the GNU C library, the rounding rule used by printf() is "bankers rounding" or "round to even". This is more correct than some other C libraries, as the C99 specification says that conversion to decimal should use the currently selected IEEE rounding mode (default bankers rounding)."

从这个答案中找到:双打的printf舍入行为

如果你想在上面进行常见的舍入圆内联,请使用 c 函数 round() 和一点数学来完成这个技巧或者你可以简单地使用 NSNumberFormatter 如你所说.

If you want to do a common rounding round inline above use the c function round() with a little math to do the trick or you can simply use NSNumberFormatter as you stated.

Objective-C 中的四舍五入

这篇关于为什么在格式化数字时 NSString 类舍入不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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