如何在 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
How to round up to the nearest 100 in JavaScript
提问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
回答by Sergey Gurin
To round upand downto the nearest 100 use Math.round
:
要向上和向下舍入到最接近的 100,请使用Math.round
:
Math.round(number/100)*100
round
vs. ceil
:
round
对比ceil
:
Math.round(60/100)*100 = 100
vs.Math.ceil(60/100)*100 = 100
Math.round(40/100)*100 = 0
vs.Math.ceil(40/100)*100 = 100
Math.round(-60/100)*100 = -100
vs.Math.ceil(-60/100)*100 = -0
Math.round(-40/100)*100 = -0
vs.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;