Rakesh Kumar
Rakesh Kumar

Reputation: 2853

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);

Upvotes: 7

Views: 7558

Answers (5)

alpha
alpha

Reputation: 1113

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

Upvotes: 5

Code Spirit
Code Spirit

Reputation: 5061

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)

Upvotes: 1

Mirza Obaid
Mirza Obaid

Reputation: 1717

enter image description here

  parseFloat(Math.round(num * 100) / 100).toFixed(2);

Upvotes: -1

kk.
kk.

Reputation: 3945

This function rounds off the values. E.g. if the value is between 9.080 to 9.084 the result would be 9.08 and if the value is 9.085 to 9.089 the result would be 9.09.

Upvotes: 0

Ajay Thakur
Ajay Thakur

Reputation: 1072

Please check, this helps you alot in understanding the logic behind this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Upvotes: 0

Related Questions