Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using division operator (/) on strings in javascript

Tags:

javascript

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)?

like image 562
Arsen Avatar asked Aug 25 '15 11:08

Arsen


1 Answers

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

like image 71
Tushar Avatar answered Nov 06 '22 13:11

Tushar