【问题标题】:PHP format decimal part of numberPHP格式数字的小数部分
【发布时间】:2017-10-06 20:24:14
【问题描述】:

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

0.000 432 532 

number_format() 仅格式化浮点的整个部分,而不是小数部分。

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

【问题讨论】:

  • @Fibbe 使用 number_format 格式化两边将删除小数部分的前导 0
  • 如何使用 numbr_format() 格式化两边

标签: php number-formatting


【解决方案1】:

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

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

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

echo $result;

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

这个有一个限制,数字不能大于99,否则数字的整数部分会开始“分解”。
但似乎你只使用了小数字。

【讨论】:

  • 但 100.005 将导致 100 。 005
  • @Mehdi 正确。我刚刚添加了那个。我是在你评论的时候写的
  • tbh 可能是最好的解决方案。我所知道的处理数千个中断等的所有 php 函数都在小数点之前
  • 限制有点严格,但对于我的目标来说它可以,因为我使用它的最大数量是 2.x
  • @Roman 我也这么认为。通常,当您有很多小数时,您的数字不会很高
【解决方案2】:

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

$input = '0.000432532';

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

// Match three digits
$regex = '/(\d{3})/';
$subst = '$1 '; // 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, '.');

这个适用于所有号码

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多