How do I format numbers to have only two decimal places?
I want that real numbers would be for example 12.92, but not 12.9241. Is it possible to d开发者_JS百科o like that?
In PHP, try 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
For PHP you can use number_format()
, for MySQL use the FORMAT()
function.
MySQL: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format
FORMAT(number, 2)
Example:
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
$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;
}
final will be 1234.56
You can multiply your number by 100, do a rounding of the result and then divide back by 100.
Or in php use the round function round function
$result=round(12.9241, 2);
精彩评论