[Javascript] Force String to Float?

Nick Fitzsimons nick at nickfitz.co.uk
Tue May 15 11:30:15 CDT 2007


On 15 May 2007, at 17:12:13, Peter Brunone wrote:

> I know that parseInt has a default number base of 8, so you want to  
> specify that second parameter -- e.g. parseInt(myNum, 10) -- to  
> make sure numbers get parsed correctly...  maybe the same thing is  
> true of parseFloat...?

Not quite ;-)

"parseInt(string, radix)" will parse a string into a number according  
to the following rules:

if the radix is specified, it will be used as the numeric base in  
which the string is to be parsed;
if the radix is not specified or is zero:
    if the string begins with the string "0x" (zero followed by x) it  
will be parsed as hexadecimal (radix 16);
    if the string begins with the character "0" (zero), it will be  
parsed as octal (radix 8);
    otherwise it will be parsed as decimal (radix 10).

So although it is always good practice to specify the radix, it is  
not true that the default radix is 8: the default radix is dependent  
on the input.

"parseFloat" does not accept a radix, or indeed any second argument.

As a general rule, unless you know for a fact that people will be  
entering non-integral numbers, or will be entering integral numbers  
in a variety of radices specified according to the rules outlined  
above, you should use "parseInt" and always specify a radix of 10.

Regards,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list