PHP 格式化数字的小数部分

PHP format decimal part of number

我有数字 0.000432532 我想像这样打破小数部分千位

0.000 432 532 

number_format()只是格式化浮点数的全部,不是小数部分。

有没有单一功能可以做到的?

不知道是否有更好的解决方案,但正则表达式可以做到。

$re = '/(\d{3})/'; // match three digits
$str = '0.000432532';
$subst = ' '; // substitute with the digits + a space

$result = preg_replace($re, $subst, $str);

echo $result;

https://regex101.com/r/xNcfq9/1

这有一个限制,数字不能大于 99 否则数字的整数部分将从 "break" 开始。
但是好像你只用了小数字。

只要您使用小于 99 的数字,Andreas 的回答就可以正常工作,但是如果您打算使用 >99 的数字,我建议这样做:

$input = '0.000432532';

// Explode number
$input = explode('.', $input);

// Match three digits
$regex = '/(\d{3})/';
$subst = ' '; // substitute with the digits + a space
// Use number format for the first part
$input[0] = number_format($input[0], 0, '', ' ');
// User regex for the second part
$input[1] = preg_replace($regex, $subst, $input[1]);

echo implode($input, '.');

这个适用于所有号码

正则表达式方法将比所有这些各种数组转换更有效,但为了论证,它可以在没有正则表达式的情况下完成:

list($int, $dec) = explode('.', $number);
$result = implode('.', [$int, implode(' ', str_split($dec, 3))]);

对于正则表达式,我认为这应该可以处理大多数情况:

$formatted = preg_replace('/(\d+\.\d{3}|\d{3})(?!$)/', ' ', $number);