-1

JavaScript writes a number with 2 decimal place and it will show 0 in decimal?

I have no worry about round off the number because I am accepting only 2 decimal place number

let num = 2.60
console.log(num) // result 2.6

It will return 2.6 but I want 2.60. I can use to.Fixed(2) but it will return in string format.

let num = 1.23
console.log(num) // result 1.23

I know to.Fixed() but it returns string. I want number format and it show 1.00 and 1.60 in number format not in the string format. I have used parseFloat(num.toFixed(2)) but it does not show last 0 value in decimal.

Imran Rafiq
  • 308
  • 2
  • 5
  • 15
  • Does this answer your question? [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – David784 Jul 19 '20 at 13:45
  • @David784 all of the answers to that old question are terrible. The fundamental issue is that JavaScript, like almost all modern mainstream languages, uses a **binary** floating point representation. – Pointy Jul 19 '20 at 13:54
  • @Pointy yea i agree, the solution to this problem in not in trying to change the number, but rather to have a different variable holding the representation in the format wanted for a certain number – ehab Jul 19 '20 at 13:59
  • 2
    Simple, you can't. If you want a visual representation keeping the decimal 0's, then you have to use a string, not any number format. – St.Nicholas Jul 19 '20 at 14:02
  • Leading and trailing zeroes are not part of a binary floating point representation as they have no affect on the actual numeric value. That's just the way things are. If you want a certain amount of zeroes to display, then you convert to a string for display purposes and leave the storage as is. – jfriend00 Jul 19 '20 at 16:13

1 Answers1

1

You can never change how the javascript engine represent float numbers, if it is a number and has enough leading zeros that the engine considers that it should cut it then it would do.

1.60 in floating point is actually more like 1.6000000000000000888, you can see that yourself by trying

console.log(1.60 === 1.6000000000000000888) // true

The solution is to use toFixed whenever you want to display the value in the format you need, and when you need to do arithmetic operations convert that value back using parseFloat - just like you did, but just have separate variables for views and arithmetic.

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
ehab
  • 7,162
  • 1
  • 25
  • 30