0

i'm following Beginning Javascript, and learning about data types conversions, more specific float and integers.

in chrome console, when i try subtraction:

parseFloat("2.1" - "0.1"); =>2

but when try the same with addition i get this:

parseFloat("2.1" + "0.1"); =>2.1

Can someone elaborate why during addition it behaves not how I would think it should?

thanks in advance

1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

0

Have a look at the results of the subtraction and addition before calling parseFloat:

"2.1" - "0.1"
=> 2

In this case, JavaScript has inferred that you want to subtract numbers, so the strings have been parsed for you before the subtraction operation has been applied. Let's have a look at the other case:

"2.1" + "0.1"
=> "2.10.1"

Here the plus operator is ambiguous. Did you want to convert the strings to numbers and add them, or did you want to concatenate the strings? Remember that "AB" + "CDE" === "ABCDE". You then have:

parseFloat("2.10.1")

Now, 2.10.1 is not a valid number, but the parsing does its best and returns 2.10 (or put more simply, 2.1).

I think what you really wanted to do is to parse the two numbers separately before adding or subtracting them. That way you don't rely on JavaScript's automatic conversion from strings to numbers, and any mathematical operation should work as you expect:

parseFloat("2.1") - parseFloat("0.1")
=> 2

parseFloat("2.1") + parseFloat("0.1")
=> 2.2
andersschuller
  • 13,509
  • 2
  • 42
  • 33