using division operator (/) on strings in javascript
Solution 1:
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
Solution 2:
Therefore my question is if it is (cross-browser) safe to use this feature...
It depends on your definition of "safe." With the division operator, yes, it's specified behavior: Each operand is converted (implicitly coerced) to a number, and then numeric division is done.
But beware of generalizing this too far. You'll be okay with /
, *
, and -
but it will bite you on +
, because if either operand to +
is a string, +
does string concatenation, not addition.
Another way that it may or may not be "safe" depending on your point of view is the implicit coercion: It uses the browser's JavaScript engine's rules for converting strings to numbers. Some older browsers went beyond the specification (which they were allowed to in the past) and treated numbers starting with a 0
as octal (base 8) rather than decimal. Naturally, end users who type in, say, "0123" as a number probably mean the number 123, not the number 83 (123
in octal = 83
decimal). JavaScript engines are no longer allowed to do that, but some older ones do.
In general, it's probably best to explicitly coerce or convert those operands. Your choices for doing so:
The unary
+
operator:value = +value
will coerce the string to a number using the JavaScript engine's standard rules for that. Any non-digits in the string (other than thee
for scientific notation) make the resultNaN
. Also,+""
is0
, which may not be intuitive.The
Number
function:value = Number(value)
. Does the same thing as+
.The
parseInt
function, usually with a radix (number base):value = parseInt(value, 10)
. The downside here is thatparseInt
converts any number it finds at the beginning of the string but ignores non-digits later in the string, soparseInt("100asdf", 10)
is100
, notNaN
. As the name implies,parseInt
parses only a whole number.The
parseFloat
function:value = parseFloat(value)
. Allows fractional values, and always works in decimal (never octal or hex). Does the same thingparseInt
does with garbage at the end of the string,parseFloat("123.34alksdjf")
is123.34
.
So, pick your tool to suit your use case. :-)