|
|
|||||
|
Ready to Use Script Archive | | | Over 5000 Free Fonts | | | Tutorials | | | Javascript Forum | | | Other Javascript Resources | | | Cheat Sheet |
Converting Strings to NumbersQuestion: How do I convert strings to numbers in JavaScript?
Answer: To convert a string to a number, use the JavaScript function
parseFloat syntax:
How it works: Examples (comments in each line give the conversion results): parseFloat('1.45kg') // 1.45 parseFloat('77.3') // 77.3 parseFloat('077.3') // 77.3 parseFloat('0x77.3') // 0 parseFloat('.3') // 0.3 parseFloat('0.1e6') // 100000
parseInt syntax:
How it works:
If there is only one argument, the number base is detected according to
the general JavaScript syntax for numbers. Strings that begin with
If the string argument cannot be parsed as an integer,
the results will be different in different browsers
(either
Examples (comments in each line give the conversion results): parseInt('123.45') // 123 parseInt('77') // 77 parseInt('077',10) // 77 parseInt('77',8) // 63 (= 7 + 7*8) parseInt('077') // 63 (= 7 + 7*8) parseInt('77',16) // 119 (= 7 + 7*16) parseInt('0x77') // 119 (= 7 + 7*16) parseInt('099') // 0 (9 is not an octal digit) parseInt('99',8) // 0 or NaN, depending on the platform parseInt('0.1e6') // 0 parseInt('ZZ',36) // 1295 (= 35 + 35*36) |
|