如何将数字格式化为仅保留两位小数?

13

我希望实数例如为12.92,而不是12.9241。是否可以这样做?

4个回答

23

在 PHP 中,试试使用number_format函数:

$n = 1234.5678;

// Two decimal places, using '.' for the decimal separator
// and ',' for the thousands separator.
$formatted = number_format($n, 2, '.', ',');
// 1,234.57

4

2
如果您不想要千位分隔符,您也可以以同样的方式使用ROUND()。 - Jordan Running

3
$number = 1234.5678;
$teX = explode('.', $number);

if(isset($teX[1])){
    $de = substr($teX[1], 0, 2);
    $final = $teX[0].'.'.$de;
    $final = (float) $final;
}else{
    $final = $number;   
}

最终结果将是1234.56


-1

您可以将数字乘以100,对结果进行四舍五入,然后再除以100。

或者在php中使用round函数round function

$result=round(12.9241, 2);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接