[英]How to round up in fraction part php
I have some value like 2.3
, 3.6
, 3.8
now I want to get value as closest fraction. 我有一定的价值像2.3
, 3.6
, 3.8
,现在我想要得到的值最接近的分数。
suppose 假设
when value is 2.3
then modified value will be 2.5
when value is 2.2
then modified value will be 2
当值为2.3
修改后的值为2.5
当值为2.2
修改后的值为2
I understand that you want to round to closest "half integer". 我了解您要舍入到最接近的“半整数”。 If so, then you can use round()
function but with a little modificators. 如果是这样,则可以使用round()
函数,但要有一些修饰符。
Because round()
returns only integers, you need to modify your value before rounding and again after rounding in reverse way to make it work. 由于round()
仅返回整数,因此您需要在舍入之前修改值,并在以相反方式舍入之后再次修改值以使其起作用。
Since you want to round with 0.5, which is 1/2, you need to first multiply your value by 2, and divide it back after. 由于您想四舍五入为0.5,即1/2,因此您需要先将值乘以2,然后再除以。
So the pattern here is: 所以这里的模式是:
$roundedVal = round($origVal*2)/2;
And examples from your question: 还有来自您问题的示例:
var_dump(round(2.3*2)/2); //2.5
var_dump(round(2.2*2)/2); //2.0
You need to look into PHP's round() function, and its optional flags. 您需要研究PHP的round()函数及其可选标志。
$myValue = -5;
echo abs($myValue); //outputs 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.