Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round negative value to 2 decimal places

I have two negative value -0.245 and -9.085. I want make them to 2 decimal places. I am using JavaScript function toFixed() but getting some weird result.

Please help me to under stand the logic behind the first example being rounded "down" but the second being rounded "up"

//Examples 1. result coming as expected
var num = -0.245
var n = num.toFixed(2); //-0.24
console.log(n);

//Examples 2. result should be -9.08
num = -9.085
n = num.toFixed(2); //-9.09
console.log(n);
like image 486
Rakesh Kumar Avatar asked Sep 29 '16 11:09

Rakesh Kumar


2 Answers

as per description in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed mention:

The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

For -0.245.toFixed(2), the value is negative and the value after 2 decimal places is -0.045, -0.045 is higher than -0.05, so the result is rounded up to -0.24

For -9.085.toFixed(2), the value is negative and the value after 2 decimal places is -0.085, -0.085 is lower than -0.08, so the result is rounded down to -9.09

Below is solution to always round up to 2 decimal places for negative value.

var num = -9.085
var output = num < 0 ? Math.floor(Math.abs(num) * 100) * -1 / 100 : num.toFixed(2)
console.log(output) //-9.08
like image 96
alpha Avatar answered Oct 02 '22 10:10

alpha


toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

Which means the result is not wrong but you expecting toFixed() to do something diffrent. If you round -9.085 to second decimal place the mathematic correct result is -9.09 (.5 round up the next decimal). What you are trying to accomplish is to remove everything after the second decimal which can be accomplished with:

parseInt(-9.085 * 100) / 100 //-9.08

alert(parseInt(-9.085 * 100) / 100)
like image 40
Code Spirit Avatar answered Oct 02 '22 09:10

Code Spirit