舍入PHP中特定小数位的十进制数

时间:2017-09-26 08:07:41

标签: php decimal rounding

如果我的变量的小数大于.3,我希望对其进行舍入,如果它的值小于或等于它将向下舍入,例如,如果我有1.34它将向前舍入为2,如果我有1.29,它将向下舍入到1,如果我有1.3,它将向下舍入到1。我不知道如何准确地做到这一点,现在我正在使用这样的圆形基本功能:

$weight = $weight/1000;
if($weight < 1) $weight = 1;
else $weight = round($weight, 0, PHP_ROUND_HALF_DOWN);

3 个答案:

答案 0 :(得分:1)

如果稍微操纵数字,可以判断小数是.3还是更高。您可以通过对值进行拼接来实现此目的,并从原始值中减去该值。检查结果是否乘以10,大于3.如果是,则表明你的结果高于x.3

$number = 1.31;

$int = floor($number);
$float = $number-$int;
if ($float*10 > 3.1)
    $result = ceil($number);
else
    $result = $int;

echo $result; // 2

答案 1 :(得分:0)

也许像这个功能?

function roundImproved($value, $decimalBreakPart = 0.3) {
    $whole = floor($value);
    $decimal = $value - $whole;
    $decimalPartLen = strlen($decimal) - 2;

    return (number_format($decimal, $decimalPartLen) <= number_format($decimalBreakPart, $decimalPartLen) ? $whole : ceil($value));
}

证明: http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a

如果需要,您可以指定“break part”。

答案 2 :(得分:0)

我让你有点破解,这里是代码

$weight = 5088;
$weight = $weight/1000;

if($weight < 1)  {
    $weight = 1;
} else {
// I get the last number (I treat the $weight as a string here)
$last_number = substr($weight, -1, 1);
// Then I get the precision (floating numbers)
$precision = strlen(substr(strrchr($weight, "."), 1));
// Then I convert it to a string so I can use some helpful string functions
$weight_str = (string) $weight;
// If the last number is less then 3
if ($last_number > 3)
   // I change it to 9 I could just change it to 5 and it would work
   // because round will round up if then number is 5 or greater
   $weight_str[strlen($weight_str) -1] = 9;  
}

}
// Then the round will round up if it's 9 or round down if it's 3 or less
$weight = round($weight_str, $precision); 
echo $weight;