Negative round value up to 2 decimal places

I have two negative values -0.245 and -9.085 . I want to make them up to two decimal places. I use the JavaScript toFixed() function, but I get some weird result.

Please help me substitute the logic behind the first example of rounding down, but the second rounds 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); 
+5
source share
5 answers

as described in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed saying:

The number is rounded if necessary, and if necessary, the fractional part is filled with zeros 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 greater than -0.05, so the result is rounded to -0.24

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

Below is a solution for rounding to two decimal places for a 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 
+2
source

Please check this will help you in understanding the logic of this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

0
source

This function rounds values. For instance. if the value is between 9.080 and 9.084, the result will be 9.08, and if the value is 9.085 - 9.089, the result will be 9.09.

0
source

enter image description here

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

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

This means the result is not wrong, but you expect toFixed() do something else. If you round -9.085 to the second decimal place, then the mathematical correct result is -9.09 (.5 round the next decimal place). What you are trying to accomplish is to delete everything after the second decimal place, which can be done with:

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

 alert(parseInt(-9.085 * 100) / 100) 
0
source

Source: https://habr.com/ru/post/1257443/


All Articles