如何格式化仅在 php 中显示 1 个小数位的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4622328/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:43:34  来源:igfitidea点击:

How can I format the number for only showing 1 decimal place in php?

php

提问by Jin Yong

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?

回答by Evan Mulawski

Use PHP's number_format

使用 PHP number_format

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

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, thisarticle is a good reference for different decimal characters and separator styles.

此外,这篇文章对于不同的十进制字符和分隔符样式是一个很好的参考。

回答by Navdeep Singh

You use the round function

您使用圆形功能

echo round(3.4445, 1); // 3.4

回答by Pawan Kumar

Use the PHP native function bcdiv

使用 PHP 原生函数bcdiv

echo bcdiv(5.98735, 1, 1);  // 5.9
echo bcdiv(5.98735, 1, 2);  // 5.98
echo bcdiv(5.98735, 1, 3);  // 5.987
echo bcdiv(-5.98735, 1, 1); // -5.9
echo bcdiv(-5.98735, 1, 2); // -5.98
echo bcdiv(-5.98735, 1, 3); // -5.987

回答by Michael Irigoyen

Number format will do this for you.

数字格式将为您做到这一点。

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

PHP: number_format

PHP:数字格式

回答by nonopolarity

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(),但请注意,有些人看到的结果比预期的要长。您还可以使用printf()sprintf()的格式为"%.1f"

回答by Teja Kantamneni

Use number_formatfunction. number_format("2.10", 1)will simply do that. Hereis the documentation.

使用number_format功能。number_format("2.10", 1)只会这样做。是文档。