我希望能够以科学格式或十进制格式打印具有给定有效数字位数的数字。我正在尝试使用 NumberFormatter,但我发现有些不一致。我也可能不完全理解 NumberFormatter 的语法。该文档没有提供很多相关示例,我很难在网上找到这些示例。
所以,下面的代码似乎产生了几乎我需要的东西
// create number formatter
$nf = new NumberFormatter('it', NumberFormatter::DECIMAL);
// force the use of significant digits? I'm not sure this is the right way of using this
// option, but if I omit this line, the following ones have no effect
$nf->setAttribute(NumberFormatter::SIGNIFICANT_DIGITS_USED,1);
// set the same value for the maximum and minimum number of significant digits should force a
// given number of s.d.
$nf->setAttribute(NumberFormatter::MIN_SIGNIFICANT_DIGITS, 3);
$nf->setAttribute(NumberFormatter::MAX_SIGNIFICANT_DIGITS, 3);
// test format: the following gives what I expect, "1,31"
// (Italian locale uses a comma for the decimal separator).
echo $nf->format(1.306);
但是,它不会产生我想要的“中间数字”。例如echo $nf->format(1.305);产生 1,30 而不是预期的 1,31。但是echo $nf->format(1.315);给出了我的期望: 1,32 。
这会影响 DECIMAL 和 SCIENTIFIC 格式。
我认为这与“ROUND_HALFEVEN”选项有关,所以我尝试添加
$nf->setAttribute(NumberFormatter::ROUNDING_MODE,NumberFormatter::ROUND_HALFUP);
但是,这似乎只“解决”了 SCIENTIFIC 格式的问题,并且只有当结果是整数时。即:如果代码中的第一行如上(DECIMAL)数字1.305;22.45; 222.5 给 1,30; 22.4;222; 而不是 1,31;22.5;223. 如果我选择 SCIENTIFIC 格式,相同的三个数字将四舍五入为整数,最后一个产生预期结果:1,00E0;2,00E0; 2,23E2。
所以,要么 HALFUP 不是解决我的问题的正确选择,要么我用错了。
当然,我可以尝试为正确的有效位数编写自己的函数(或从示例中复制它),但我认为在 NumberFormatter 中设置正确的选项应该为我做到这一点。
任何见解都值得赞赏。
弗朗切斯科