如何在 JavaScript 中四舍五入到最接近的 100

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19621455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:12:49  来源:igfitidea点击:

How to round up to the nearest 100 in JavaScript

javascriptmath

提问by Curtis

I want to round up to the nearest100 all the time whether or not the value is 101 or 199 it should round up to 200. For example:

我想一直四舍五入到最接近的100,无论值是 101 还是 199,它都应该四舍五入到 200。例如:

var number = 1233;
//use something like Math.round() to round up to always 1300

I'd like to always round up to the nearest 100, never round down, using jQuery.

我想总是四舍五入到最接近的 100,从不四舍五入,使用 jQuery。

回答by MightyPork

Use Math.ceil(), if you want to always round up:

使用Math.ceil(), 如果你想总是四舍五入:

Math.ceil(number/100)*100

回答by meagar

No part of this requires jQuery. Just use JavaScript's Math.ceil:

这其中没有任何部分需要 jQuery。只需使用 JavaScript 的Math.ceil

Math.ceil(x / 100.0) * 100

回答by Sergey Gurin

To round upand downto the nearest 100 use Math.round:

向上向下舍入到最接近的 100,请使用Math.round

Math.round(number/100)*100

roundvs. ceil:

round对比ceil

Math.round(60/100)*100 = 100vs. Math.ceil(60/100)*100 = 100

Math.round(40/100)*100 = 0vs. Math.ceil(40/100)*100 = 100

Math.round(-60/100)*100 = -100vs. Math.ceil(-60/100)*100 = -0

Math.round(-40/100)*100 = -0vs. Math.ceil(-40/100)*100 = -0

Math.round(60/100)*100 = 100对比 Math.ceil(60/100)*100 = 100

Math.round(40/100)*100 = 0对比 Math.ceil(40/100)*100 = 100

Math.round(-60/100)*100 = -100对比 Math.ceil(-60/100)*100 = -0

Math.round(-40/100)*100 = -0对比 Math.ceil(-40/100)*100 = -0

回答by Joe Bennouna

This is an easy way to do it:

这是一个简单的方法:

((x/100).toFixed()*100;