如何格式化数字只有两位小数?

时间:2010-01-02 18:43:16

标签: php mysql

我希望实数可以是例如12.92,但不是12.9241。有可能这样做吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

对于PHP,您可以使用number_format(),因为MySQL使用FORMAT()函数。

MySQL:http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format

FORMAT(number, 2)

示例:

mysql> SELECT FORMAT(12332.123456, 4);
       -> '12,332.1235

PHP:http://php.net/manual/en/function.number-format.php

$number = 1234.5678;
$formatted_number = number_format($number, 2, '.', '');
// 1234.56

答案 2 :(得分:0)

$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

答案 3 :(得分:-1)

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

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

$result=round(12.9241, 2);