将数字转换为字符串。
- var myNumber = 32;
- console.log(myNumber.toString()); // 32
进制转换。
- var myNumber = 32;
- console.log("(十进制)Decimal " + myNumber.toString(10)); // Decimal 32
- console.log("(十六进制)Hexadecimal " + myNumber.toString(16)); // Hexadecimal 20
- console.log("(八进制)Octal " + myNumber.toString(8)); // Octal 40
- console.log("(二进制)Binary " + myNumber.toString(2)); // Binary 100000
返回一个字符串,包含进行舍入的数字并使用指数表示法,可选参数定义小数点后面的位数。
- var x = 9.656;
- console.log(x.toExponential()); // 9.656e+0
- console.log(x.toExponential(2)); // 9.66e+0
- console.log(x.toExponential(4)); // 9.6560e+0
- console.log(x.toExponential(6)); // 9.656000e+0
将数字四舍五入为给定的位数(几位小数)。
- var x = 9.656;
- console.log(x.toFixed(0)); // 10
- console.log(x.toFixed(2)); // 9.66
- console.log(x.toFixed(4)); // 9.6560
- console.log(x.toFixed(6)); // 9.656000
返回一个指定数字数量的字符串,数字指定为多少,小数点前后数字共有多少个。
- var x = 9.656;
- console.log(x.toPrecision()); //9.656
- console.log(x.toPrecision(2)); //9.7
- console.log(x.toPrecision(5)); //9.6560
- x = 99.656;
- console.log(x.toPrecision(5)); //99.656
把变量转换为数字。
- console.log(Number(true)); // 1
- console.log(Number(true)); // 0
- console.log(Number("10.3")); // 10.3
- console.log(Number("10,3")); // NaN
- console.log(Number("Bill")); // NaN
把字符串转换为数字。数字开头的字符串都可以转换为数字。
- console.log(parseInt("10")); //10
- console.log(parseInt("10.11")); //10
- console.log(parseInt("10 years")); //10
- console.log(parseInt("10years")); //10
- console.log(parseInt("10 att - 你好")); //10
- console.log(parseInt("years 10")); //NaN
字符串转换为浮点数字。
- console.log(parseFloat("10")); //10
- console.log(parseFloat("10.11")); //10.11
- console.log(parseFloat("10 years")); //10
- console.log(parseFloat("10years")); //10
- console.log(parseFloat("10 att - 你好")); //10
- console.log(parseFloat("years 10")); //NaN
返回 Javascript 中可能的最大值。
- var x = Number.MAX_VALUE;
- console.log(x); // 1.7976931348623157e+308
返回 JavaScript 中可能的最小数字。
- var x = Number.MIN_VALUE;
- console.log(x); // 5e-324
表示无穷大。
- var x = Number.POSITIVE_INFINITY;
- console.log(x); // Infinity
溢出时返回 POSITIVE_INFINITY:
- var x = 1 / 0;
- console.log(x); // Infinity
表示负无穷大。
- var x = Number.NEGATIVE_INFINITY;
- console.log(x); // -Infinity
溢出时返回 NEGATIVE_INFINITY:
- var x = -1 / 0;
- console.log(x); // -Infinity
对变量、表达式或值使用数字属性,将返回 undefined:
- var x = 6;
- console.log(x.MAX_VALUE); // undefined