0

I need to round the numbers.

46.38 >>> 46.40
46.40 >>> 46.40
46.41 >>> 46.50

I am using round($price, 1) but this converts 46.41 to 46.40. But i need 46.50

nas
  • 2,289
  • 5
  • 32
  • 67
  • 1
    If you save the original, compare it to the rounded value and then check if the rounded value is smaller just add 0.1? – Randommm Jun 15 '23 at 09:08
  • 1
    So you want to round up? Try `round($price + 0.05, 1, PHP_ROUND_HALF_DOWN)` – Rob Eyre Jun 15 '23 at 09:08
  • @RobEyre `46.40 >>> 46.50` If its 46.40 then it needs to be 46.40 – nas Jun 15 '23 at 09:10
  • 1
    Does this answer your question? [PHP to round up to the 2nd decimal place](https://stackoverflow.com/questions/22991021/php-to-round-up-to-the-2nd-decimal-place) – Ricky Mo Jun 15 '23 at 09:11
  • Basically, multiply the number up to the precision you want, call `ceil()`. then divide it back to the original exponent. – Ricky Mo Jun 15 '23 at 09:12
  • 1
    If I do `$price = 46.40; echo round($price + 0.05, 1, PHP_ROUND_HALF_DOWN);` it gives me `46.4` – Rob Eyre Jun 15 '23 at 09:12

2 Answers2

3

You need ceil instead of round, but it does not come with precision out of the box. You need to add this functionality yourself like e.g.

function myceil(int|float $number, int $precision, int $decimals) {
    return number_format(ceil($number*(10**$precision))/(10**$precision), 2);
}

You can then use it as:

echo myceil(46.38,1, 2).PHP_EOL;
echo myceil(46.40,1, 2).PHP_EOL;
echo myceil(46.41,1, 2).PHP_EOL;

This will output:

46.40
46.40
46.50

3v4l code

Note: The number_format is added to additionally control the decimals that will be shown in the end. It is not (strictly speaking) necessary and also causes the function output to be a string rather than a float.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
2

I recommend this approach:

$roundedPrice = round($price + 0.05, 1, PHP_ROUND_HALF_DOWN);

This produces the outputs required from the inputs given.

... or more generally, if $precision is the number of digits to the right of the decimal point,

$roundedPrice = round($price + (1/10**$precision)/2, $precision, PHP_ROUND_HALF_DOWN);
Rob Eyre
  • 717
  • 7