使用 PHP 格式化百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14525393/
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
Format percentage using PHP
提问by user1032531
I would like to format 0.45 as 45%.
我想将 0.45 格式化为 45%。
I know I can just do something like FLOOR($x*100).'%', but wonder if there is a better way (better is defined as more standard and not necessarily faster).
我知道我可以做类似的事情FLOOR($x*100).'%',但想知道是否有更好的方法(更好被定义为更标准,不一定更快)。
One thought is http://php.net/manual/en/class.numberformatter.php. Is this a better way? Has anyone used it and can you show an example? Thanks
一种想法是http://php.net/manual/en/class.numberformatter.php。这是更好的方法吗?有没有人使用过它,你能举个例子吗?谢谢
回答by Colin M
Most likely, you want roundinstead of floor. But otherwise, that would be the most "standard" way to do it. Alternatively you could use sprintfsuch as:
最有可能的是,您想要round而不是floor. 但否则,这将是最“标准”的方法。或者,您可以使用sprintf例如:
sprintf("%.2f%%", $x * 100)which would print the percentage of $x with two decimal points of precision, and a percentage sign afterwards.
sprintf("%.2f%%", $x * 100)这将打印带有两个小数点精度的 $x 的百分比,然后是一个百分比符号。
The shortest way to do this via NumberFormatteris:
通过执行此操作的最短方法NumberFormatter是:
$formatter = new NumberFormatter('en_US', NumberFormatter::PERCENT);
print $formatter->format(.45);
It would be better to do this if your application supports various locales, but otherwise you're just adding another line of code for not much benefit.
如果您的应用程序支持各种语言环境,最好这样做,否则您只是添加另一行代码,并没有太大好处。
回答by Mr. B
You can also use a function.
您还可以使用函数。
function percent($number){
return $number * 100 . '%';
}
and then use the following to display the result.
然后使用以下内容显示结果。
percent($lab_fee)

