我是php的新手,我正在尝试使用number_format:
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
与标题一样,我的目标是修改小数点和千位分隔符而不更改小数位数,如下所示:
$Num=123456.789;
$Num2=number_format ($Num, [decimals as in $Num], ",", "'" );
我的结果应该是:
$Num2="123'456,789";
修改
我需要一个未知小数位数的代码
答案 0 :(得分:3)
您可以使用NumberFormatter。
您仍然需要指定一定数量的小数位数,但您可以使用足够高的值并保持良好状态。它不像数字的数字真的是任意的。它与您的precision ini setting绑定。
$formatter = new NumberFormatter("en_US", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 42);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "'");
$formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, ",");
echo $formatter->format(123456.7891234); // 123'456,7891234
答案 1 :(得分:0)
你可以这样做(首先看看@Gordon的答案 - 它会更好):
<?php
function extendedNumberFormat($num, $decimalSeparator, $thousandSeparator) {
$asStr = strval($num);
$exploded = explode('.', $asStr);
$int = $exploded[0];
$decimal = isset($exploded[1]) ? $exploded[1] : null;
$result = number_format($int, 0, ".", $thousandSeparator);
if ($decimal !== null) {
$result .= $decimalSeparator . $decimal;
}
return $result;
}
echo extendedNumberFormat(123456.789, ',', "'") . "\n";
echo extendedNumberFormat(123456.7891, ',', "'") . "\n";
echo extendedNumberFormat(123456, ',', "'") . "\n";
//123'456,789
//123'456,7891
//123'456