12种最常见的JavaScript数字方法
web前端开发
共 4789字,需浏览 10分钟
·
2020-12-27 13:38
1、 Number()
// Example 1
let x = '10'
let num = Number(x)
console.log(num) // Output: 10
console.log(num * 9) // Output: 90
// Example 2
let x = true
let num = Number(x)
console.log(num) // Output: 1
console.log(num + 9) // Output: 10
//Example 3
let x = false
let num = Number(x)
console.log(num) // Output: 0
console.log(num + 9) // Output: 9
2、 parseInt()
// Example 1
let x = '10.99'
let num = parseInt(x)
console.log(num) // Output: 10
// Example 2
let x = '7 days'
let num = parseInt(x)
console.log(num) // Output: 7
// Example 3
let x = 'day 7'
let num = parseInt(x)
console.log(num) // Output: NaN
3、parseFloat()
// Example 1
let x = '10.99'
let num = parseFloat(x)
console.log(num) // Output: 10.99
// Example 2
let x = '2.49 3.99'
let num = parseFloat(x)
console.log(num) // Output: 2
// Example 3
let x = 'day 7'
let num = parseFloat(x)
console.log(num) // Output: NaN
4、 toString()
// Example 1
let x = 10
let num = x.toString()
console.log(num) // Output: '10'
// Example 2
let x = 10
let num = x.toString(2)
console.log(num) // Output: 1010
5、 toExponential()
// Example 1
let x = 456.789
let num = x.toExponential()
console.log(num) // Output: 4.56789e+2
// Example 2
let x = 456.789
let num = x.toExponential(2)
console.log(num) // Output: 4.57e+2
// Example 1
var num = 4.56789;
console.log(num.toFixed()) // Output : 5
// Example 2
var num = 4.56789;
console.log(num.toFixed(2)) // Output : 4.57
7、 toPrecision()
// Example 1
var num = 456.789;
console.log(num.toPrecision()) // Output : 456.789
// Example 2
var num = 456.789;
console.log(num.toPrecision(2)) // Output : 4.6
8、valueOf()
let x = 45
let num = x.valueOf()
console.log(num) // Output: 45
console.log(typeof num); // Output: Number
9、toLocaleString()
let num = 226537.883;
//US English
console.log(num.toLocaleString('en-US')); //Output: 226,537.883
// Romanian (Romania)
console.log(num.toLocaleString('ro-RO')); //Output: 226.537,883
// Standard French (especially in France)
console.log(num.toLocaleString('fr-FR')); //Output: 226 537,883
10、 isInteger()
//Example 1
let x = 10
let num = Number.isInteger(x)
console.log(num) // Output: true
//Example 2
let x = 10.99
let num = Number.isInteger(x)
console.log(num) // Output: false
//Example 3
let x = "10"
let num = Number.isInteger(x)
console.log(num) // Output: false
11、 isFinite()
//Example 1
let x = 10
let num = Number.isFinite(x)
console.log(num) // Output: true
//Example 2
let x = -10.99
let num = Number.isFinite(x)
console.log(num) // Output: true
//Example 3
let x = "10"
let num = Number.isFinite(x)
console.log(num) // Output: false
12、 isSafeInteger()
Number.isSafeInteger(220)//输出:true
Number.isSafeInteger(-220)//输出:true
Number.isSafeInteger(2.2)//输出:false
Number.isSafeInteger(978678367894123469469410320213)//输出:false
评论