如何格式化仅在 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
How can I format the number for only showing 1 decimal place in 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
回答by Michael Irigoyen
Number format will do this for you.
数字格式将为您做到这一点。
$num = 2.10;
number_format($num, 1);