Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 27, 2021 12:51 am GMT

5 Useful JS Number Methods

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.00console.log(20.248.toFixed(1)) // 20.2console.log(Math.PI.toFixed(3)) // 3.142

Number.isInteger()

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

Number.isNaN()

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

console.log(Number.isNaN(1)); // falseconsole.log(Number.isNaN('1')); // falseconsole.log(Number.isNaN('Aya Bouchiha')); // falseconsole.log(Number.isNaN("")); // falseconsole.log(Number.isNaN(" ")); // falseconsole.log(Number.isNaN(Number.NaN)); // trueconsole.log(Number.isNaN(NaN)); // trueconsole.log(Number.isNaN('NaN')); // falseconsole.log(Number.isNaN(0 / 0)); // trueconsole.log(Number.isNaN(undefined)); // falseconsole.log(Number.isNaN(null)); // falseconsole.log(Number.isNaN([])); // falseconsole.log(Number.isNaN(true)); // false

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.141592653589793console.log(pi.toPrecision(1)) // 3console.log(pi.toPrecision(3)) // 3.14console.log(pi.toPrecision(101)) // error

Number.isFinite()

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

console.log(Number.isFinite(1)) // trueconsole.log(Number.isFinite('10')) // falseconsole.log(Number.isFinite('Aya Bouchiha')) // falseconsole.log(Number.isFinite(Infinity)) // falseconsole.log(Number.isFinite(-Infinity))  // falseconsole.log(Number.isFinite(NaN)) // false

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


Original Link: https://dev.to/ayabouchiha/5-useful-js-number-methods-43l4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To