How to round to nearest Thousand?

前端 未结 8 657
独厮守ぢ
独厮守ぢ 2020-12-06 03:59

How Do I round a number to its nearest thousand?

function round($var) {
    // Round it
}
8条回答
  •  星月不相逢
    2020-12-06 05:06

    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.

提交回复
热议问题