Skip to content Skip to sidebar Skip to footer

Math.ceil Not Working With Negative Floats

I am trying to create a RoundUp function with help of Math.ceil it working fine with positive number but do not round up the negative numbers Here is what i am trying var value = -

Solution 1:

The Math.ceil method does actually round up even for negative values. The value -12 is the closest integer value that is at higher than -12.369754.

What you are looking for is to round away from zero:

value = value >= 0 ? Math.ceil(value) : Math.floor(value);

Edit:

To use that with different number of decimal points:

// it seems that the value is actually a string// judging from the parseFloat calls that you havevar value = '-12.369754';
var decimalPoints = 0;

// parse it once
value = parseFloat(value);

// calculate multipliervar m = Math.pow(10, decimalPoints);

// round the value    
value = (value >= 0 ? Math.ceil(value * m) : Math.floor(value * m)) / m;

console.log(value);

Demo: http://jsfiddle.net/Guffa/n7ecyr7h/3/

Solution 2:

Math.ceil(-1.1234) will be -1.12 because in negative -1.12 > -1.1234. I think you misunderstood mathematically.

Post a Comment for "Math.ceil Not Working With Negative Floats"