1

Is there a way to add trailing zeros to a number in javascript?

For example: 47.0 instead of 47 or 0.0 instead of 0

when I return the numbers in a json, the zeros disapper.

I need them to be numbers and not strings so .toFixed(2) doesn't help.

Thanks!

Gil
  • 63
  • 2
  • 8
  • 2
    Numbers (aka IEEE754 Doubles) are represented in binary exponential notation. They can not have trailing (or leading... or whatever) zeroes. – Vatev Nov 12 '13 at 19:23
  • So you take the string and convert them to numbers when you need to perform an operation with them. – epascarello Nov 12 '13 at 19:42

2 Answers2

4

The number 47.0 is the same number as 47, so the only way to change its representation is to make it a string.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • 1
    Spot on. It's then the job of the client/receiver of the JSON to decide how many decimal places to show that number to, if need be. If you really need to specify that the number is to exactly 1 d.p., you'd have to pass an additional value `decimalPlaces = 1`... But I can't really see the sense in that – Shai Nov 12 '13 at 19:24
  • 3
    Also, even if you manage to hack your JSON serializer to output 47.0 instead of 47 it will not matter, because the parser on the other side will ignore it anyway. – Vatev Nov 12 '13 at 19:28
4

No. What you want is a specific presentation, which most simple types has no concept of.

Anyway, when serialized into a JSON request or response it would still be converted to a string, but the receiving end shouldn't care at all if it's represented as 46.0, 46.00 or 46.000 unless it has the "" around it.

DennisK
  • 420
  • 4
  • 8