带money_format的数千个分隔符


Thousands separator with money_format?

$numval = 12345.50;

期望输出:

12 345,50

逗号而不是点不是问题,但是如何使千位分隔符成为空格?

我注意到带有空格的 PHP 货币格式,但这不是重复的帖子。 使用 number_format 是毫无疑问的,因为它对输入值进行了舍入。我根本不允许通过它传递的值四舍五入。

是否有一种内置方法可以完全执行number_format()所做的事情,但不舍入值,或者我必须编写自己的函数来执行此操作?

如果四舍五入是不可能的,那么浮点值也是如此。如果您不想要舍入,则必须返回到整数,因为浮点运算并不精确。在这种情况下,您必须自己实现格式化功能。

如果您正在处理金钱,则尤其如此。例如,为什么不使用双精度或浮点数来表示货币?

这看起来像您要使用的函数版本:

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

所以例如:

$newNumber = number_format($oldNumber, 2, ",", " ");

欲了解更多信息,请查看 http://php.net/manual/en/function.number-format.php

来自 number_format() 页面的这条评论(我修改了函数以匹配number_format默认值)。

要防止舍入:

function fnumber_format($number, $decimals=0, $dec_point='.', $thousands_sep=',') {
        if (($number * pow(10 , $decimals + 1) % 10 ) == 5)  //if next not significant digit is 5
            $number -= pow(10 , -($decimals+1));
        return number_format($number, $decimals, $dec_point, $thousands_sep);
}