php 将浮点数格式化为两位小数

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

Format a float to two decimal places

phpstring

提问by Niharika Gupta

I want to format a float value I have to two decimal places.

我想将浮点值格式化为两位小数。

For example if I have a float for a price of 5.2, I want it to be formatted as 5.20.

例如,如果我有一个价格为 的浮点数5.2,我希望它的格式为5.20.

回答by GBD

Try number_format:

尝试number_format

echo number_format("5.2",2)

回答by FluffyHyman

You'll want to use printfor sprintf. You can read more about it in the php docs.

你会想要使用printfsprintf。您可以在php docs 中阅读有关它的更多信息。

回答by John Parker

If you're simply trying to ensure a number is displayed with two decimal places, you could also use number_format, or (if this is a currency value) money_format.

如果您只是想确保数字显示为两位小数,您还可以使用number_format或(如果这是货币值)money_format

e.g.: echo number_format('5.2', 2);

例如: echo number_format('5.2', 2);

回答by Danura Aditya

Try this:

尝试这个:

number_format((float)$foo, 2, '.', '');