by Julian M Bucknall

A hotdog stand on the road to JavaScript enlightenment for C# developers. Firebug is our companion.

In this episode we take a quick look at converting a string to a number and the `parseInt`

function.

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 `"042"`

, not a number. Why? It certainly looks like it should produce a numeric expression. Unfortunately, when one of the terms in an additive expression is a string, JavaScript makes the result of the addition a string and not the other way around. So the `0`

gets converted to `'0'`

and is then concatenated with the other string. This is one of the gotchas of working with dynamically typed JavaScript: the plus operator can either mean numeric addition (as we're used to) or string concatenation (as we're *also* used to in C#), but JavaScript assumes the latter if there's a string term in the expression. Beware.

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.

However, it all seems a little hit-and-miss. So JavaScript provides two utility functions: `parseFloat`

and `parseInt`

. Both take a string and return a number, with the second forcing the number returned to be an integer value (but, remember, not an integer proper since JavaScript numbers are always floating point values). To us C# developers, the way they act is a little disconcerting: they stop parsing when they reach an invalid character, and return the number found up until that point. So:

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 `NaN`

.

`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.

Now playing:

New Order - **The Beach**

(from *Power, Corruption & Lies*)

Loading links to posts on similar topics...

## 3 Responses

## #1 Dew Drop - March 28, 2009 | Alvin Ashcraft's Morning Dew said...

28-Mar-09 12:56 PMPingback from Dew Drop - March 28, 2009 | Alvin Ashcraft's Morning Dew

## #2 JavaScript for C# programmers: convert string to integer - Julian M Bucknall said...

28-Mar-09 8:32 PMThank you for submitting this cool story - Trackback from DotNetShoutout

## #3 nphp101 said...

08-Jan-10 6:35 PMVery informative! You ROCK!!!

## Leave a response

Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.

`_emphasis_`

`**strong**`

`[text](url)`

``IEnumerable``

`* an item`

`1. an item`

`> Now is the time...`

## Preview of response