简体   繁体   English

圆形函数php

[英]Round function php

Maybe the question is simple, but I can't find the answer.也许问题很简单,但我找不到答案。 What I need to do is to round number to 2 places after comma.我需要做的是在逗号后将数字四舍五入到 2 位。 Im using this:我使用这个:

round(($data/$count*100), 2)

And when I get number like:当我得到这样的数字时:

60.36036036036012 and : 37.83783783783808 is OK, because it's: 60.36 and 37.84

But why this:但为什么会这样:

1.8018018018018036

Is rounded to this:四舍五入为:

1.8000000000000003 

How to round always to 2 places, after comma?逗号后如何始终舍入到 2 个位置?

You should get 1.8 unless you use something like old PHP version with some sort of related bugs.你应该得到1.8除非你使用类似旧 PHP 版本的东西,但有一些相关的错误。 Still, if you want to see 1.80 you need to format output string, otherwise trailing zero will be stripped by default.尽管如此,如果您想看到1.80您需要格式化输出字符串,否则默认情况下将删除尾随零。 The most flexible approach would be to use sprintf() formatting, like this:最灵活的方法是使用sprintf()格式,如下所示:

$val = 1.8000000000000003;
printf("%.02f", round( $val, 2 ));

which would produce这会产生

1.80

The key is "%.02f" which means you want to format (f)loating point value, with two digits after dot, padded with 0 when needed (like this case).关键是“%.02f”,这意味着您要格式化(f)浮点值,点后有两位数字,需要时用0填充(如本例)。

See the sprintf() docs for more about available formatting possibilites.有关可用格式可能性的更多信息,请参阅 sprintf()文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM