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

时间:2022-03-04 11:17:31

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。有可能这样做吗?

3 个解决方案

#1


23  

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

#2


4  

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

#3


-1  

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中使用圆函数轮函数

$result=round(12.9241, 2);

#1


23  

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

#2


4  

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

#3


-1  

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中使用圆函数轮函数

$result=round(12.9241, 2);