0

I noticed that if I do in JavaScript:

var dict = { "foo" : 1.0 };

when retrieving dict I will get:

{ foo : 1 }

What is the rationale behind this? And what is the preferred way of avoiding it (I currently convert 1.0 to a string)?

adrianp
  • 2,491
  • 5
  • 26
  • 44
  • 1
    http://stackoverflow.com/questions/5179836/difference-between-floats-and-ints-in-javascript – Ian May 22 '13 at 13:55

1 Answers1

4

JavaScript doesn't convert floats to integers. What you're seeing is the behavior of some diagnostic tool, whatever it is you're using to look at the value of that variable. JavaScript numbers are always double-precision floating point, except in the middle of some bitwise operations (and that's a transient condition).

Because all numbers are floating point, it's not necessary to use an explicit decimal when initializing a variable to a value that's got no fractional part. That is, 1 and 1.0 are exactly the same value in a JavaScript program.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I actually use the JSON representation of JS objects in a Java application, and there you can get into some issues if you don't read a float as expected. So I guess there's not much to do about this? – adrianp May 22 '13 at 13:57
  • @adrianp (I'm no Java guru, but) won't an integer automatically be converted to a float if you provide it? For example, `double d = 1;` works, but not the opposite: `int i = 1.2;` – Ian May 22 '13 at 13:59
  • 2
    @adrianp JSON is its own syntax with its own rules. How JSON numbers are converted to a Java data structure depends on what your Java JSON parser wants to do, and that has nothing whatsoever to do with JavaScript. When a JSON object is parsed on the **JavaScript** side, then `1` will result in the same value as `1.0`. – Pointy May 22 '13 at 14:03
  • @Ian Yes, that is true; I was not very clear, my issue is when I do `json.getFloat()`. – adrianp May 22 '13 at 14:35