simple guy
simple guy

Reputation: 655

Round up decimal number for specific decimal places in PHP

I want to round up my variable if it's decimal larger than .3 and if it's lower or equal it will round down, for example if i have 1.34 it will round up to 2, if i have 1.29 it will round down to 1, and if i have 1.3 it will round down to 1. I don't know how to do this precisely, right now i'm using the round basic function like this:

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

Upvotes: 2

Views: 994

Answers (3)

barat
barat

Reputation: 1058

Maybe something like this function?

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));
}

Proof: http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a

You can specify "break part" if you want.

Upvotes: 0

Qirel
Qirel

Reputation: 26490

If you manipulate the numbers a bit, you can figure out if the decimals are .3 or higher. You achieve this by flooring the value, and subtract that from the original value. Check if the result of that, multiplied by 10, is greater than 3. If it is, you've got something above 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

Upvotes: 2

teeyo
teeyo

Reputation: 3755

I made you a little hack, here's the code

$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;

Upvotes: 0

Related Questions