In this episode we take a quick look at converting a string to a number and the
Every now and then we'd like to convert a number expressed as a string into a variable of type
number so that we can do some calculations with it. There are several ways to go about this, and we saw one a while back when we were looking at the expression evaluator.
var stringValue = "42"; var value = +stringValue; console.log(typeof value); // outputs "number"
Here we set
stringValue to a string, and then convert it to a number by the simple expedient of using the unary plus operator. Since that's a little hard to spot sometimes, we can also use other numeric expressions that force the conversion:
var stringValue = "42"; var value2 = 0 + stringValue; var value3 = 1 * stringValue; console.log(typeof value2); // outputs "string" console.log(typeof value3); // outputs "number"
Except… the first one here produces a
string variable with value
0 gets converted to
The second, multiplicative, expression works just fine as we'd expect, since there is no other meaning for the
'*' operator but numeric multiplication. So, the string is coerced into a number and the multiplicative identity operation takes place.
var stringValue = "3.14 is the value of PI"; var value = parseFloat(stringValue); console.log(value); // outputs "3.14"
parseFloat parsed the string up until the space character after 3.14 and returned that value back.
parseInt works in the same way, but the arithmetic expressions I was showing above do not:
var stringValue = "3.14 is the value of PI"; var value = +stringValue; console.log(value); // outputs "NaN"
Here, as you can see, the type coercion failed, and so
value was set to
parseInt has another quirk as well. If the number in the string starts with a zero character, the value is assumed to be expressed in octal. So:
var stringValue = "078"; var value = parseInt(stringValue); console.log(value); // outputs "7"
Since the character
'8' is not a valid octal character, the parsing stops and the value 7 is returned. In fact, if the string begins with
'0x', the number is assumed to be represented in hexadecimal.
But, wait. There's even more.
parseInt accepts a second parameter, the radix. If this is missing (that is,
undefined), the string is assumed to be base 10, except for the two exceptions noted. If you want to force it to be be parsed in base 10, you should explicitly state 10 as the radix.
var stringValue = "078"; var value = parseInt(stringValue, 10); console.log(value); // outputs "78"
In fact, rather than assume anything about the string being parsed, it's best to specify the radix parameter at all times. Make your assumptions explicit.
New Order - The Beach
(from Power, Corruption & Lies)