数字格式PHP欧洲格式(= 3.213.124,4355),十进制不带0

时间:2018-11-07 12:46:29

标签: php

我想按照以下方式在PHP中转换数字:

100000 -> 100.000
3213 -> 3.213
54523.321 -> 54.523,321
42324.00 -> 42.324
3412.1 -> 3.412,1

所以我想拥有。作为千位分隔符和作为十进制分隔符,我不想在小数点中使用较少的0。我该怎么办?

我知道我可以使用float来去除小数点后的0。而且我知道我可以使用number_format替换千位/十进制分隔符,但是在这种情况下,您还必须定义小数位数,并且十进制中将得到0 ...

2 个答案:

答案 0 :(得分:5)

使用number_format()如下:

$number = 1234.5600;
$nb = number_format($number, 2, ',', '.'); // 1.234,56

它将自动删除小数点末的所有零。

答案 1 :(得分:0)

我自己找到了答案(使用/更改了在number_format()的注释中找到的代码):

function number_format_unchanged_precision($number, $dec_point='.', $thousands_sep=','){
    if($dec_point==$thousands_sep){
        trigger_error('2 parameters for ' . __METHOD__ . '() have the same value, that is "' . $dec_point . '" for $dec_point and $thousands_sep', E_USER_WARNING);
        // It corresponds "PHP Warning:  Wrong parameter count for number_format()", which occurs when you use $dec_point without $thousands_sep to number_format().
    }
    $decimals = strlen(substr(strrchr($number, "."), 1));

    return number_format($number, $decimals, $dec_point, $thousands_sep);
}

这里还有一个包含舍入但不添加无用0的函数:(我认为普通的number_format()函数应该像这样工作...)

function number_format_without_zeroindecimal($number, $maxdecimal, $dec_point='.', $thousands_sep=','){
    if($dec_point==$thousands_sep){
        trigger_error('2 parameters for ' . __METHOD__ . '() have the same value, that is "' . $dec_point . '" for $dec_point and $thousands_sep', E_USER_WARNING);
        // It corresponds "PHP Warning:  Wrong parameter count for number_format()", which occurs when you use $dec_point without $thousands_sep to number_format().
    }
    $decimals = strlen(substr(strrchr(round($number,$maxdecimal), "."), 1));

    return number_format($number, $decimals, $dec_point, $thousands_sep);
}