我有各种各样的长数字,并且我试图编写一个函数来正确格式化它们。有人可以帮我吗?
我已经尝试过“ 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”,则应四舍五入到小数点后两位,并添加千位分隔符(例如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
请尝试以下操作:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句