Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round large non-decimal numbers, up and down with php

Tags:

php

How do I round larger numbers in php.

NOTE: I have aready tried the round function and can not seem to get it to work as i need

for example:

Say i have 4 listing in a database and they have 4 different prices.

    1st Price = 5,783

    2nd Price = 19,647

    3rd Price = 12,867

    4th Price = 23,647

Now we determin that the lowest price in the databae would be 5,783

and the highest price is 23,647.


now what i want to do is round down the lowest price to say the nearest 500 or 1000 or even 5000


example of nearset 1000

lowest price 5,783 rounded down = 5000

highest price 23,647 rounded up = 24000

like image 806
Wesley Avatar asked Dec 16 '22 00:12

Wesley


2 Answers

You can use this function:

function nearest($num, $divisor) {
  $diff = $num % $divisor;
  if ($diff == 0)
    return $num;
  elseif ($diff >= ceil($divisor / 2))
    return $num - $diff + $divisor;
  else
    return $num - $diff;
}

Call it like this:

nearest(23647, 5000);

Similar functions, but when you want to decide for yourself in which direction to round:

function roundUp($num, $divisor) {
  $diff = $num % $divisor;
  if ($diff == 0)
    return $num;
  else
    return $num - $diff + $divisor;
}


function roundDown($num, $divisor) {
  $diff = $num % $divisor;
  return $num - $diff;
}
like image 62
Emil Vikström Avatar answered Jan 01 '23 16:01

Emil Vikström


Look at the round in the php manual. The fist example says:

<?php
    echo round(3.4);         // 3
    echo round(3.5);         // 4
    echo round(3.6);         // 4
    echo round(3.6, 0);      // 4
    echo round(1.95583, 2);  // 1.96
    echo round(1241757, -3); // 1242000
    echo round(5.045, 2);    // 5.05
    echo round(5.055, 2);    // 5.06
?>

I think you are looking for

round(23647, -3) 

I've not checked this but it shold work (see manual).

If you want to kill the ',' you can use number_format

like image 44
waXve Avatar answered Jan 01 '23 16:01

waXve