0

I am trying to round down numbers using PHP.

I have managed to do this if the value has a decimal place, using this method below.

$val = floor($val * 2) / 2;
echo 'hello'. $val;

If the value I am trying to round down doesn't have a decimal place and the above code is not working.

The values I am trying to round down.

32456 => 32000

4567 => 4000

38999 => 38000
LF00
  • 27,015
  • 29
  • 156
  • 295
Chris
  • 1
  • 1
  • If the number doesn't have a fraction, `$val * 2` will be an integer as well, so `floor()` won't change it. – Barmar Aug 23 '16 at 00:53
  • refer to [round thousand hundrard etc.](https://stackoverflow.com/q/43932648/6521116) – LF00 May 25 '17 at 15:38

1 Answers1

5

There are a few ways to do this. The most common way (for rounding down to the nearest 1000) would be something like this:

function roundDown1000($n)
{
    return floor($n / 1000) * 1000;
}

More generally:

function roundDown($n, $increment)
{
    return floor($n / $increment) * $increment;
}

If you wanted, you could also do $n - ($n % 1000), but this will get weird results for $n < 0.

elixenide
  • 44,308
  • 16
  • 74
  • 100