php 想要在浮点数后精确显示 2 位数字

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

want to display exactly 2 digits after floating point

phpfloating-point

提问by Rukmi Patel

I want to convert floating value of 8 digits after floating point in to 2 digits after floating point ..

我想将浮点后的 8 位浮点值转换为浮点后的 2 位..

Eg. $a = 2.200000 ==> 2.20

例如。$a = 2.200000 ==> 2.20

I am using round function of php. Problem with round is if my number is 2.200000 it converts number in 2.2 . I want output as 2.20

我正在使用php的round函数。round 的问题是,如果我的数字是 2.200000,它会将数字转换为 2.2 。我想输出为 2.20

Can any one suggest the possible way?

任何人都可以提出可能的方法吗?

Actual code

实际代码

$price = sprintf ("%.2f", round(($opt->price_value + ($opt->price_value * $this->row->prices[0]->taxes[0]->tax_rate)), 2));

i want out put like if my floating number is 2.2000000. then it should return me 2.20. but right now it is returning me 2.2

如果我的浮动数字是 2.2000000,我想把它放出来。那么它应该返回我 2.20。但现在它让我返回 2.2

回答by wallyk

This does what I think you are asking for:

这符合我认为您的要求:

<?php

$a = 2.20032324;
$f = sprintf ("%.2f", $a);
echo "$a rounded to 2 decimal places is '$f'\n";

$a = 2.2000000;
$f = sprintf ("%.2f", $a);
echo "$a rounded to 2 decimal places is '$f'\n";

results:

结果:

[wally@lenovoR61 ~]$ php t.php
2.20032324 rounded to 2 decimal places is '2.20'
2.2 rounded to 2 decimal places is '2.20'

I added two test cases

我添加了两个测试用例

回答by Smruti

Try the below code, You can get your result.

试试下面的代码,你可以得到你的结果。

       $a = 2.200000;
       echo number_format((float)$a,2,'.','');

回答by na8ur

try $val = round($a * 100)/100;

尝试 $val = round($a * 100)/100;