如何格式化数字只显示PHP中的1位小数?

时间:2022-07-30 16:57:25

Does any one know how can I format the number and limited it to only show 1 decimal place in php?

有没有人知道如何格式化数字并限制它只在PHP中显示1位小数?

Example:

How can I format the number 2.10 to 2.1 in php?

如何在php中格式化数字2.10到2.1?

5 个解决方案

#1


16  

Use PHP's number_format

使用PHP的number_format

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

Example:

$one_decimal_place = number_format(2.10, 1);

$ one_decimal_place = number_format(2.10,1);

If you ever need to convert it back to a float:

如果您需要将其转换回浮点数:

$the_float_value = floatval($one_decimal_place);

$ the_float_value = floatval($ one_decimal_place);

Also, this article is a good reference for different decimal characters and separator styles.

此外,本文是不同的十进制字符和分隔符样式的良好参考。

#2


5  

You use the round function

您使用圆形功能

echo round(3.4445, 1); // 3.4

#3


1  

you can use round() with a precision of 1, but note that some people see longer than expected result. You can also use printf() or sprintf() with a format of "%.1f"

你可以使用精度为1的round(),但请注意,有些人看到的结果比预期的要长。您还可以使用格式为“%.1f”的printf()或sprintf()

#4


0  

Use number_format function. number_format("2.10", 1) will simply do that. Here is the documentation.

使用number_format函数。 number_format(“2.10”,1)就是这么做的。这是文档。

#5


0  

Number format will do this for you.

数字格式将为您完成此操作。

$num = 2.10;
number_format($num, 1);

PHP: number_format

#1


16  

Use PHP's number_format

使用PHP的number_format

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

Example:

$one_decimal_place = number_format(2.10, 1);

$ one_decimal_place = number_format(2.10,1);

If you ever need to convert it back to a float:

如果您需要将其转换回浮点数:

$the_float_value = floatval($one_decimal_place);

$ the_float_value = floatval($ one_decimal_place);

Also, this article is a good reference for different decimal characters and separator styles.

此外,本文是不同的十进制字符和分隔符样式的良好参考。

#2


5  

You use the round function

您使用圆形功能

echo round(3.4445, 1); // 3.4

#3


1  

you can use round() with a precision of 1, but note that some people see longer than expected result. You can also use printf() or sprintf() with a format of "%.1f"

你可以使用精度为1的round(),但请注意,有些人看到的结果比预期的要长。您还可以使用格式为“%.1f”的printf()或sprintf()

#4


0  

Use number_format function. number_format("2.10", 1) will simply do that. Here is the documentation.

使用number_format函数。 number_format(“2.10”,1)就是这么做的。这是文档。

#5


0  

Number format will do this for you.

数字格式将为您完成此操作。

$num = 2.10;
number_format($num, 1);

PHP: number_format