[Javascript] Force String to Float?

Peter Brunone peter at brunone.com
Tue May 15 11:34:22 CDT 2007


Cheers Nick; it's been a while since I read up on that subject.

----------------------------------------

From: Nick Fitzsimons nick at nickfitz.co.uk

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/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20070515/2e110742/attachment.htm>


More information about the Javascript mailing list