javascript string to number

String to integer number

<script>
var n = parseInt('100',10); // 100; you want to use radix of 10 so you get a decimal number even with a leading 0
parseInt('123.45') // 123
parseInt('77') // 77
parseInt('077',10) // 77
parseInt('77',8) // 63 (= 7 + 7*8) base=8
parseInt('077') // 63 (= 7 + 7*8) base=8
parseInt('77',16) // 119 (= 7 + 7*16) base=16
parseInt('0x77') // 119 (= 7 + 7*16) base=16
parseInt('099') // 0 (9 is not an octal digit)
parseInt('99',8) // NaN (not-a-number value)
parseInt('0.1e6') // 0
 
var n = Math.floor('100.01'); // 100; floor automatically converts string to number
 
var n = Math.round('100'); // 100; equivalent to Math.round('100',0)
</script>

String to float number

<script>
parseFloat('1.5kg') // 1.5
parseFloat('55.3') // 55.3
parseFloat('055.3') // 55.3
parseFloat('0x55.3') // 0
parseFloat('.3') // 0.3
parseFloat('0.1e5') // 10000
</script>

The ultimate string-to-number conversion table:

x parseInt(x) parseFloat(x) Number(x) +x ~~x
"123" 123 123 123 123 123
"-123" -123 -123 -123 -123 -123
"123.45" 123 123.45 123.45 123.45 123
"-123.45" -123 -123.45 -123.45 -123.45 -123
"12e5" 12 1200000 1200000 1200000 1200000
"012" 12 12 12 12 12
"0xBABE" 47806 0 47806 47806 47806
"0xFFFFFFFF" 4294967295 0 4294967295 4294967295 -1
"123456789012345678" 123456789012345680 123456789012345680 123456789012345680 123456789012345680 -1506741424
"" NaN NaN 0 0 0
"123foo" 123 123 NaN NaN 0
"123.45foo" 123 123.45 NaN NaN 0
" 123 " 123 123 123 123 123
"foo" NaN NaN NaN NaN 0
null NaN NaN 0 0 0
undefined NaN NaN NaN NaN 0
true NaN NaN 1 1 1
false NaN NaN 0 0 0
{} NaN NaN NaN NaN 0
{} NaN NaN 125 125 125

code for table:

format = function(rows) {
	var lens = [];
 
	rows.forEach(function(row) {
		row.forEach(function(col, n) {
			lens[n] = Math.max(lens[n] || 0, col.length);
		})
	});
 
	return rows.map(function(row) {
		return row.map(function(col, n) {
			return new Array(lens[n] - col.length + 1).join(" ") + col;
		}).join(" | ")
	}).join("\n");
}
 
xs = [
    "123", "-123", "123.45", "-123.45", "12e5", "012", "0xBABE", 
	"0xFFFFFFFF", "123456789012345678",
    "", "123foo", "123.45foo", "  123   ", "foo", 
	null, window.foo, true, false, 
	{}, 
	{valueOf:function() { return 125 }}
]
 
table = [[
	"x",
	"parseInt(x)",
	"parseFloat(x)",
	"Number(x)",
	"+x",
	"~~x"
]].concat(xs.map(function(x) {
    return [
	    String(JSON.stringify(x)),
	    String(parseInt(x)),
	    String(parseFloat(x)),
	    String(Number(x)),
	    String(+x),
	    String(~~x)
	]
}))
 
document.body.innerHTML = "[pre]" + format(table) + "[/pre]"

Leave a Reply

Your email address will not be published. Required fields are marked *