37

How Do I round a number to its nearest thousand?

function round($var) {
    // Round it
}
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
Steven Hammons
  • 1,774
  • 8
  • 24
  • 33

8 Answers8

70

PHP allows negative precision for round such as with:

$x = round ($x, -3); // Uses default mode of PHP_ROUND_HALF_UP.

Whereas a positive precision indicates where to round after the decimal point, negative precisions provide the same power before the decimal point. So:

n    round(1111.1111,n)
==   ==================
 3   1111.111
 2   1111.11
 1   1111.1
 0   1111
-1   1110
-2   1100
-3   1000

As a general solution, even for languages that don't have it built in, you simply do something like:

  • add 500.
  • divide it by 1000 (and truncate to integer if necessary).
  • multiply by 1000.

This is, of course, assuming you want the PHP_ROUND_HALF_UP behaviour. There are some who think that bankers rounding, PHP_ROUND_HALF_EVEN, is better for reducing cumulative errors but that's a topic for a different question.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
8
rounded_number = round(original_number, -3);

http://php.net/manual/en/function.round.php

Amber
  • 507,862
  • 82
  • 626
  • 550
7

Just a small change, may help to round up!

$x = ceil(220.20 / 1000) * 1000;
echo $x;
Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
6

Here's an answer to round up to the next thousand:

abs(round(($a - 500), -3)) . "\n";

500-999 then round to 0 and 1000-1999 round to 1000, etc.

If you want it to start at 1000, then just do

abs(round(($a + 500), -3)) . "\n";

Cheers!

Theodore R. Smith
  • 21,848
  • 12
  • 65
  • 91
4

Use the round function as mentioned by other posters round($number, -3).

You can also, divide your number by 1,000, round to nearest whole number then multiply by 1,000.

Also, if you want to round up, you can divide by 1,000, negate the quotient, coerce it to an integer, negate it again and then multiply it by 1,000.

Icode4food
  • 8,504
  • 16
  • 61
  • 93
3

Just for your information simple calculation from Mikel answer is faster than round():

Test name       Repeats         Result          Performance     
calculation     10000           0.030229 sec    +0.00%
round           10000           0.040981 sec    -35.57%

Test source here.

Community
  • 1
  • 1
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
2

from: http://us3.php.net/manual/en/function.round.php

$x = round ( $x, -3 );
bensiu
  • 24,660
  • 56
  • 77
  • 117
2

For positive integers:

function round($var) {
    return ($var + 500) / 1000 * 1000;
}
Mikel
  • 24,855
  • 8
  • 65
  • 66
  • 3
    OP asked for it to be called `round()`. If it already exists, call it something else! ;-) – Mikel Mar 01 '11 at 03:53