简体   繁体   中英

parseFloat addition in Javascript, help me understand how it works

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM