Round a float up to the next integer in javascript

JavascriptFloating PointRounding

Javascript Problem Overview


I need to round floating point numbers up to the nearest integer, even if the number after the point is less than 0.5.

For example,

  • 4.3 should be 5 (not 4)
  • 4.8 should be 5

How can I do this in JavaScript?

Javascript Solutions


Solution 1 - Javascript

Use the Math.ceil[MDN] function

var n = 4.3;
alert(Math.ceil(n)); //alerts 5

Solution 2 - Javascript

Use ceil

var n = 4.3;
n = Math.ceil(n);// n is 5

Solution 3 - Javascript

Round up to the second (0.00) decimal point:

 var n = 35.85001;
 Math.ceil(n * 100) / 100;	// 35.86

to first (0.0):

 var n = 35.800001;
 Math.ceil(n * 10) / 10;	// 35.9

to integer:

 var n = 35.00001;
 Math.ceil(n);				// 36

jsbin.com

Solution 4 - Javascript

Use

Math.ceil( floatvalue );

It will round the value as desired.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHeba GomaahView Question on Stackoverflow
Solution 1 - JavascriptPeter OlsonView Answer on Stackoverflow
Solution 2 - JavascriptNicola PeluchettiView Answer on Stackoverflow
Solution 3 - JavascriptArtem PView Answer on Stackoverflow
Solution 4 - JavascriptAshwin SinghView Answer on Stackoverflow