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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With