php 如何将数字格式化为只有两位小数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1992406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I format numbers to have only two decimal places?
提问by good_evening
I want that real numbers would be for example 12.92, but not 12.9241. Is it possible to do like that?
我希望实数是例如 12.92,而不是 12.9241。有可能这样做吗?
回答by John Feminella
In PHP, try number_format:
在 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
回答by Clash
For PHP you can use number_format(), for MySQL use the FORMAT()function.
对于 PHP,您可以使用number_format(),对于 MySQL,您可以使用该FORMAT()函数。
MySQL: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format
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
PHP:http: //php.net/manual/en/function.number-format.php
$number = 1234.5678;
$formatted_number = number_format($number, 2, '.', '');
// 1234.56
回答by Bill Stephen
$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
最终将是 1234.56
回答by Patrick
You can multiply your number by 100, do a rounding of the result and then divide back by 100.
您可以将您的数字乘以 100,对结果进行四舍五入,然后再除以 100。
Or in php use the round function round function
或者在php中使用round函数round函数
$result=round(12.9241, 2);

