Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 848
Curtis Avatar asked Oct 27 '13 18:10

Curtis


People also ask

How do you round up to 100?

Rounding to the nearest 100 To round a number to the nearest 100, look at the tens digit. If the tens digit is 5 or more, round up. If the tens digit is 4 or less, round down. The tens digit in 3281 is 8.

How do you round up in JavaScript?

ceil() The Math. ceil() function always rounds a number up to the next largest integer.

How do you round price in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.


2 Answers

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

Math.ceil(number/100)*100 
like image 190
MightyPork Avatar answered Sep 23 '22 14:09

MightyPork


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

like image 33
Sergey Gurin Avatar answered Sep 22 '22 14:09

Sergey Gurin