0

Is the following correct? And why?

x = 7;
y = 7.00;
z = x + y;
console.log(z);

Result:

14

I expect the log result to be "14.00".

Scotty
  • 71
  • 1
  • 4
  • already answered really so have a looky here. http://stackoverflow.com/questions/3612744/javascript-remove-insignificant-trailing-zeros-from-a-number – EasyBB Jul 13 '15 at 01:58
  • 1
    Javascript doesn't actually have an "int" type: all numbers are floats. For currency, you might want to use something like `z.toFixed(2)` for display purposes. – Curt Jul 13 '15 at 01:59
  • @Curt: Actually, for currency, it would be best to do all calculation in integral values, then divide by `100` when displaying (when, yes, you'd display them just as you show); as decimal values are imprecise. Even if the integral values are stored as floats, they are precise up to `9007199254740991`, unlike decimal numbers, which cannot be precise due to how floats function. – Amadan Jul 13 '15 at 02:02
  • 1
    That doesn't answer the question, EasyBB. – Scotty Jul 13 '15 at 02:04
  • @Amadan. I'm not sure you understood what I was saying. There is no "integral" type in Javascript: there is only numeric, which is floating point. I'm not suggesting that Scotty use floats--he has no choice. – Curt Jul 13 '15 at 02:11
  • @Curt: No, apparently you don't understand what I am saying. I just said there is no integral *type* in my post; but there are certainly integral *values*. If you want to store `7.23`, store `723` instead, and remember that it is two digits off; i.e. do everything in cents. Why? Because `7.23` part cannot be correctly represented in IEEE754, while `723` can. When you need to display, dividing by `100` will be close enough that the display is correct. But if you do calculations on `7.23`, you will eventually end up with the `0.1 + 0.2 == 0.30000000000000004` "bug" (only worse the more you do). – Amadan Jul 13 '15 at 02:13

1 Answers1

5

A 99% true statement: There is no "dynamic typing int/float" in JavaScript because there are no ints or floats in JavaScript. console.log will write the most compact representation. In fact, console.log(7.00) displays 7.

The more correct statement: integers are internally available in JavaScript (as result of bit-operations, mostly), but all numbers that reach your program are floats.

Finally, there is no reason why console.log should display anything to two decimals, unless the most compact representation had two decimals (like 7.23).

Amadan
  • 191,408
  • 23
  • 240
  • 301