JavaScript The Number Object

please click here for more wordpress cource

In JavaScript, the Number object is a built-in object that represents a numerical value. It can be used to perform mathematical operations, and provides several methods for formatting and manipulating numbers.

Here are some basic examples of using the Number object:

  1. Creating a number:
let num = new Number(10); // creates a number object with a value of 10

Alternatively, you can create a number using the literal syntax:

let num = 10; // creates a primitive number with a value of 10
  1. Checking if a value is a number:
Number.isNaN(NaN); // true
Number.isNaN("hello"); // false
Number.isFinite(10); // true
Number.isFinite(Infinity); // false
  1. Converting a string to a number:
let str = "10";
let num = Number(str); // converts the string to a number
  1. Formatting a number:
let num = 1234.5678;
num.toFixed(2); // returns "1234.57"
num.toExponential(2); // returns "1.23e+3"
num.toPrecision(4); // returns "1235"
  1. Performing mathematical operations:
let num1 = 10;
let num2 = 5;
num1 + num2; // returns 15
num1 - num2; // returns 5
num1 * num2; // returns 50
num1 / num2; // returns 2
Math.pow(num1, 2); // returns 100 (10 raised to the power of 2)

Note that JavaScript has a number of quirks when it comes to handling numbers, such as the fact that there is no distinction between integers and floats, and that certain calculations can result in unexpected precision errors. It’s important to be aware of these quirks when working with numbers in JavaScript.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *