Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

php - How to round to nearest Thousand?

How Do I round a number to its nearest thousand?

function round($var) {
    // Round it
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...