php 打印小数点后两位数的PHP浮点数?

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

Printing PHP float with 2 digits after the decimal point?

phpfloating-pointdecimal

提问by Nachshon Schwartz

Is there an easy way to echoa float number with a specific amount of digits after the decimal point?

有没有一种简单的方法来echo获得小数点后具有特定位数的浮点数?

For example: $sum = 3.1234566768;I would like to echo $sum and get: 3.12.

例如:$sum = 3.1234566768;我想 echo $sum 并 get: 3.12

回答by Andrew Hall

use number_format()

使用 number_format()

number_format($sum,2);

回答by hsz

Try with:

尝试:

$sum = 3.1234566768;
$rounded = round($sum, 2);

回答by Joey

echo number_format($sum, 2); // 3.12

回答by Jawad Saeed

echo number_format((float)$ans, 4, '.', '');

I think this will work out

我认为这会解决