logo

NJP

Useful Number methods in JavaScript

Import · Sep 19, 2020 · article

The toString() method is what it sounds, returns the number as a string. However, if you provide a parameter, such as 2, 8, or 16 it will return binary, octal or hexadecimal value respectively.

var num = 123;
num.toString();
// "123"
(100 + 44).toString();
// "144"

2. Toexponential

The toExponential() method returns a string, with a number rounded and written using exponential notation. The parameter is optional. It is an integer between 0 and 20 representing the number of digits in the notation after the decimal point. If nothing is provided, it is set to as many digits as necessary to represent the value.

var num = 3.414;
num.toExponential(2);
//3.414e+0

3. Tofixed

The toFixed() method returns a string, with the number written and specified number of decimals. Here also parameter is optional. It represents the number of digits after the decimal. By default, it is set to 0.

var num = 3.414;
num.toFixed(2);
//3.41

4. Toprecision

The toPrecision() method returns a string, with a number written with a specified length.

var num = 3.414;
num.toPrecision(2);
//3.4

5. Valueof

The valueOf() method returns a number as a number.

var num = 123;
num.valueOf();
//123

6. Number

The Number() method can be used to convert JavaScript variables to numbers.

Number(true);          //returns 1
Number(false);         //returns 0
Number("10");          //returns 10
Number("10.43");       //returns 10.43
Number("2,54");        //returns NaN

7. Parseint

The parseInt() method parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.

parseInt("10");             //returns 10
parseInt("10.43");          //returns 10
parseInt("10 20 30");       //returns 10
parseInt("1000 cupcakes");  //returns 1000 & not delicious cupcakes
parseInt("dogs 1000");      //returns NaN

8. ParseFloat

The parseFloat() method parses a string and returns a number. Spaces are allowed. Only the first number is returned.

parseFloat("10");             //returns 10
parseFloat("10.43");          //returns 10.43
parseFloat("10 20 30");       //returns 10
parseFloat("1000 dogs");      //returns 1000
parseFloat("dogs 1000");      //returns NaN

I hope this article helpful. Please mark it as helpful and bookmark if you like it.

“In learning you will teach, and in teaching you will learn.” ― Phil Collins

Thanks,

Phanindra.

View original source

https://www.servicenow.com/community/developer-articles/useful-number-methods-in-javascript/ta-p/2321117