Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I realized that in javascript all 101/100, "101"/100, 101/"100" and "101"/"100" result in 1.01 (checked on Chrome, FF and IE11). But I cannot find a piece of documentation regarding this behaviour.

Therefore my question is if it is (cross-browser) safe to use this feature, and if it is a good practice to do so (or rather to use parseInt before division if the variable can be a string)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

When you use / on strings, the strings are implicitly converted to numbers and then division operation is performed.

This may work in all browsers, but it's always good practice to convert to number explicitly using parseInt or parseFloat or other method.

parseInt("101", 10) / 100

Or

parseFloat("101") / 100

ECMAScript Specifications for Division Operator


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...