var x = parseInt("1000", 10); // You want to use radix 10// So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
一元加
如果您的字符串已经是整数形式:
var x = +"1000";
地板()
如果您的字符串是或可能是浮点数并且您想要一个整数:
var x = Math.floor("1000.01"); // floor() automatically converts string to number
var rounded = Math.floor(Number("97.654")); // other options are Math.ceil, Math.roundvar fixed = Number("97.654").toFixed(0); // rounded rather than truncatedvar bitwised = Number("97.654")|0; // do not use for large numbers
~~"3000000000.654" === -1294967296// This is the same asNumber("3000000000.654")|0"3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit"300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers
要正确处理较大的数字,您应该使用舍入方法
Math.floor("3000000000.654") === 3000000000// This is the same asMath.floor(Number("3000000000.654"))
var num = Number("999.5"); //999.5var num = parseInt("999.5", 10); //999var num = parseFloat("999.5"); //999.5var num = +"999.5"; //999.5
此外,任何Math操作都会将它们转换为数字,例如…
var num = "999.5" / 1; //999.5var num = "999.5" * 1; //999.5var num = "999.5" - 1 + 1; //999.5var num = "999.5" - 0; //999.5var num = Math.floor("999.5"); //999var num = ~~"999.5"; //999
function atoi(array) {
// Use exp as (length - i), other option would be// to reverse the array.// Multiply a[i] * 10^(exp) and sum
let sum = 0;
for (let i = 0; i < array.length; i++) {let exp = array.length - (i+1);let value = array[i] * Math.pow(10, exp);sum += value;}
return sum;}
function parseIntSmarter(str) {// ParseInt is bad because it returns 22 for "22thisendsintext"// Number() is returns NaN if it ends in non-numbers, but it returns 0 for empty or whitespace strings.return isNaN(Number(str)) ? NaN : parseInt(str, 10);}