如何用零舍入/格式化长数字?



我有各种各样的长数字,我正在尝试编写一个函数来正确格式化它们。有人可以帮助我吗?

我已经尝试了"number_format()"和"round()"但这并不能解决我的问题。

我想像下面这样四舍五入:

1024.43  --> 1,024.43  
0.000000931540 --> 0.000000932  
0.003991 --> 0.00399  
0.3241 --> 0.324
1045.3491 --> 1,045.35

所以这意味着,如果数字大于"0",它应该四舍五入到小数点后 2 位并添加千位分隔符(如 6,554.24(,如果数字小于"1",则每当数字出现在零之后时,它应该四舍五入到 3 位数字(例如 0.0003219 到 0.000322 或 0.2319 到 0.232(

编辑: 这同样适用于"-"值。例如:

-1024.43  --> -1,024.43  
-0.000000931540 --> -0.000000932  
-0.003991 --> -0.00399  
-0.3241 --> -0.324
-1045.3491 --> -1,045.35

适应 https://stackoverflow.com/a/48283297/2469308

  • 在两种单独的情况下处理此问题。
  • 对于 -1 到 1 之间的数字;我们需要计算要舍入的位数。然后,使用 number_format(( 函数我们可以得到结果。
  • 否则,只需使用十进制数字设置为 2 的 number_format(( 函数。

请尝试以下操作:

function customRound($value)
{
if ($value > -1 && $value < 1) {
// define the number of significant digits needed
$digits = 3;
if ($value >= 0) {
// calculate the number of decimal places to round to
$decimalPlaces = $digits - floor(log10($value)) - 1;
} else {
$decimalPlaces = $digits - floor(log10($value * -1)) - 1;
}
// return the rounded value
return number_format($value, $decimalPlaces);
} else {
// simply use number_format function to show upto 2 decimal places
return number_format($value, 2);
} 
// for the rest of the cases - return the number simply
return $value;
}

Rextester 演示

$x = 123.456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";
$x = 1.23456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";
$x = 0.0123456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";
$x = 0.0000123456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";
$x = 0.000000123456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";
$x = 0.00000000123456;
echo number_format($x, max(2, 3 - ceil(log10(abs($x))))) . "n";

输出:

123.45
1.23
0.0123
0.0000123
0.000000123
0.00000000123

基本上,这始终保持最少 2 个十进制数字到 3 个有效数字。

但是,由于浮点在内部处理的方式(作为 2 的幂而不是 10 的幂(,因此存在一些问题。像0.10.001这样的数字不能精确地存储,所以它们实际上存储为0.09999999...或类似的东西。在这种情况下,它似乎计算错误,并用比应有的更有效的数字给你答案。

您可以尝试通过允许公式的误差幅度来抵消这种现象:

number_format($x, max(2, 3 - ceil(log10(abs($x))) - 1e-8))

但这可能会导致其他不良影响。您将不得不进行测试。

最新更新