Number Class

JavaScript cung cấp lớp đối tượng Number chứa các phương thức dùng để thao tác với dữ liệu dạng số.

isFinite And isInteger

Cú pháp:

  • Kiểm tra có phải là số hữu hạn hay không: Number.isFinite(num) hoặc isFinite(num).
  • Kiểm tra có phải là số nguyên hay không: Number.isInteger(num).

Ví dụ:

console.log(Number.isFinite(2 / 0)) // false
console.log(Number.isFinite(20 / 5)) // true
console.log(Number.isFinite(0 / 0)) // false
 
console.log(Number.isInteger(999999999)) // true
console.log(Number.isInteger(0.2)) // false
console.log(Number.isInteger(Math.PI)) // false

Convert to Int

Cú pháp:

Number.parseInt(str, radix)

Với radix là cơ số.

Dạng rút gọn:

parseInt(str, radix)

Chuyển từ chuỗi sang số nguyên:

console.log(parseInt('10', 10))           // 10
console.log(parseInt('10.00', 10))        // 10
console.log(parseInt('238,21', 10))       // 238
console.log(parseInt('237.22', 10))       // 237
console.log(parseInt('34 56 78', 10))     // 34
console.log(parseInt(' 37 ', 10))         // 37
console.log(parseInt('18 is my age', 10)) // 18

Chuyển từ số chấm động sang số nguyên:

console.log(parseInt(1.1, 10))                  // 1
console.log(parseInt(0.5, 10))                  // 0
console.log(parseInt(0.9, 10))                  // 0
console.log(parseInt(0.9999999999, 10))         // 0
console.log(parseInt(0.999999999999999999, 10)) // 1

Chuyển từ chuỗi số thập lục phân sang số thập phân:

console.log(parseInt('f', 16))        // 15
console.log(parseInt('a', 16))        // 10
console.log(parseInt('fc', 16))       // 252
console.log(parseInt('ffffffff', 16)) // 4294967295

Chuyển từ số chuỗi số nhị phân sang số thập phân:

console.log(parseInt('00000000', 2)) // 0
console.log(parseInt('10100101', 2)) // 165
console.log(parseInt('10000000', 2)) // 128
console.log(parseInt('01010101', 2)) // 85

Convert From String to Float

Cú pháp:

Number.parseFloat(str)

Dạng rút gọn:

parseFloat(str)

Ví dụ:

console.log(parseFloat('10'))           // 10
console.log(parseFloat('10.00'))        // 10
console.log(parseFloat('238,21'))       // 238
console.log(parseFloat('237.22'))       // 237.22
console.log(parseFloat('34 56 78'))     // 34
console.log(parseFloat(' 37 '))         // 37
console.log(parseFloat('18 is my age')) // 18

Convert From Number to String

Ta có thể dùng phương thức toFixed(n) để chuyển từ chuỗi sang số với n chữ số sau dấu thập phân.

var numberObject = 1234.56789
 
console.log(numberObject.toFixed())  // '1235'
console.log(numberObject.toFixed(1)) // '1234.6'
console.log(numberObject.toFixed(6)) // '1234.567890'

Hoặc cũng có thể dùng phương thức toPrecision(n) để chuyển từ chuỗi sang số với tổng số lượng chữ số là n.

list
from [[JS Number]]
sort file.ctime asc