DEV Community

loading...
Cover image for 5 Useful JS Number Methods

5 Useful JS Number Methods

Aya Bouchiha
Full stack web developer
・2 min read

Hi everybody, I'm Aya Bouchiha, todya, we will discuss 5 useful Number Object Methods toFixed() and isInteger().

Number.prototype.toFixed()

  • toFixed(digits) returns as a string the specified number rounded to a given number of decimals.
const price = 742;
console.log(price.toFixed(2)) // 742.00
console.log(20.248.toFixed(1)) // 20.2
console.log(Math.PI.toFixed(3)) // 3.142
Enter fullscreen mode Exit fullscreen mode

Number.isInteger()

  • isInteger(num): is a static method used to check if the given value is an integer.
console.log(Number.isInteger(-1)) // true
console.log(Number.isInteger(400.00)) // true
console.log(Number.isInteger(657.1540)) // false
console.log(Number.isInteger(Math.PI)) // false
Enter fullscreen mode Exit fullscreen mode

Number.isNaN()

isNaN(num) : is a static method used to check if the given value is not a number

console.log(Number.isNaN(1)); // false
console.log(Number.isNaN('1')); // false
console.log(Number.isNaN('Aya Bouchiha')); // false
console.log(Number.isNaN("")); // false
console.log(Number.isNaN(" ")); // false
console.log(Number.isNaN(Number.NaN)); // true
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN('NaN')); // false
console.log(Number.isNaN(0 / 0)); // true
console.log(Number.isNaN(undefined)); // false
console.log(Number.isNaN(null)); // false
console.log(Number.isNaN([])); // false
console.log(Number.isNaN(true)); // false
Enter fullscreen mode Exit fullscreen mode

Number.prototype.toPrecision()

toPrecision(precision): this method formats the specified number to a the given precision Where 1 <= precision <= 100

const pi = Math.PI;
console.log(pi.toPrecision()) //3.141592653589793
console.log(pi.toPrecision(1)) // 3
console.log(pi.toPrecision(3)) // 3.14
console.log(pi.toPrecision(101)) // error
Enter fullscreen mode Exit fullscreen mode

Number.isFinite()

isFinite(num): is a static method that checks if the given number is finite.

console.log(Number.isFinite(1)) // true
console.log(Number.isFinite('10')) // false
console.log(Number.isFinite('Aya Bouchiha')) // false
console.log(Number.isFinite(Infinity)) // false
console.log(Number.isFinite(-Infinity))  // false
console.log(Number.isFinite(NaN)) // false
Enter fullscreen mode Exit fullscreen mode

Summary

  • toFixed(digits) returns as a string the specified number rounded to a given number of decimals.

  • isInteger(num): checks if the given value is an integer.

  • isNaN(num): checks if the given value is not a number.

  • toPrecision(len): formats the specified number to the given precision.

  • isFinite(num): checks if the given number is finite.

References

To Contact Me:

Have a great day

Discussion (0)