How to round up to the nearest 100 in JavaScript
I want to round up to the nearest 100 all the time whether or not the value is 101 or 199 it should round up to 200. For example:
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.
Use Math.ceil()
, if you want to always round up:
Math.ceil(number/100)*100
To round up and down to the nearest 100 use Math.round
:
Math.round(number/100)*100
round
vs. 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
No part of this requires jQuery. Just use JavaScript's Math.ceil
:
Math.ceil(x / 100) * 100
This is an easy way to do it:
((x/100).toFixed()*100;
Simplest solution would be:
Math.round(number/100)*100