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