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
305 views
in Technique[技术] by (71.8m points)

decimal - JavaScript: Rounding Down in .5 Cases

I am in a situation where a JavaScript function produces numbers, such as 2.5. I want to have these point five numbers rounded down to 2, rather than the result of Math.round, which will always round up in such cases (ignoring the even odd rule), producing 2. Is there any more elegant way of doing this than subtracting 0.01 from the number before rounding? Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Just negate the input and the output to Math.round:

var result = -Math.round(-num);

In more detail: JavaScript's Math.round has the unusual property that it rounds halfway cases towards positive infinity, regardless of whether they're positive or negative. So for example 2.5 will round to 3.0, but -2.5 will round to -2.0. This is an uncommon rounding mode: it's much more common to round halfway cases either away from zero (so -2.5 would round to -3.0), or to the nearest even integer.

However, it does have the nice property that it's trivial to adapt it to round halfway cases towards negative infinity instead: if that's what you want, then all you have to do is negate both the input and the output:

Example:

function RoundHalfDown(num) {
  return -Math.round(-num);
}

document.write("1.5 rounds to ", RoundHalfDown(1.5), "<br>");
document.write("2.5 rounds to ", RoundHalfDown(2.5), "<br>");
document.write("2.4 rounds to ", RoundHalfDown(2.4), "<br>");
document.write("2.6 rounds to ", RoundHalfDown(2.6), "<br>");
document.write("-2.5 rounds to ", RoundHalfDown(-2.5), "<br>");

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

...