Вопрос

I am trying to check if a number which is inside a variable got a decimal number above 50 , or less than 50. Then depending on if it's 50 or higher, round the decimal number to 99 , and if it's less, round it to 00.

Here is a piece of my code:

public function roundPrice($price)
{
return round( (ceil($price) - 0.01), 2);
}

It makes all decimal numbers round up to 99 . I would need only decimals which are 50 or higher to be rounded in 99, and 49 or less become 00.

How could I achieve this in PHP ? Many thanks, I'm stuck here and don't know much how to do that.

Это было полезно?

Решение

On the off chance OP actually meant decimal places where 1.36 becomes 1.00 and 1.60 becomes 1.99.

Probably more elegant solutions, but here's one:

function roundPrice($price)
{
    $intVal = intval($price);
    if ($price - $intVal < .50) return (float)$intVal;
    return $intVal + 0.99;
}

http://codepad.org/5hIdQh4w

Другие советы

You're not really rounding, so just be direct about it.

public function roundPrice($price)
{
    if($price >= 50)
    {
        return 99;
    }
    else
    {
        return 0;
    }
}

Your stated problem does not handle the $price being equal to 50. I made the assumption that the value of exactly 50 rounds up to 99.

This modifies your function to return the decimal value if it's 50 or above and 0 otherwise.

public function roundPrice($price)
{
   $decValue = round( (ceil($price) - 0.01), 2);

   if ($decValue >= 50) return $decValue;
   else return 0;
}

I would need only decimals which are 50 or higher to be rounded in 99, and 49 or less become 00.

Strange requirement but:

public function roundPrice($price)
{
  return $price >= 50 ? 99 : sprintf("%02s", 0);
}

For numbers greater than or equal to 50, it would return 99 and for numbers less than 50, it would return 00

I think you want this:

public function roundPrice($price) {
    $p = round($price, 0);
    if( ceil($price) == $p) {
        return $p - 0.01;
    }
    return $p;
}

This returns X.99 for values >= X.5 and X.00 for all other values.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top