Javascript Number toFixed()

Introduction

The Javascript Number toFixed() method formats a number using fixed-point notation.

numObj.toFixed([digits])
Parameter Optional Meaning
digitsOptional The number of digits after the decimal point

digits may be a value between 0 and 20, inclusive.

If this argument is omitted, it is treated as 0.

The toFixed() method returns a string representation of a number with a specified number of decimal points:

let num = 10; 
console.log(num.toFixed(2));  // "10.00" 

Here, the toFixed() method is given an argument of 2, which indicates how many decimal places should be displayed.

If the number has more than the given number of decimal places, the result is rounded to the nearest decimal place:

let num = 10.005; 
console.log(num.toFixed(2));  // "10.01" 

Using toFixed()

let numObj = 12345.6789;
let a = numObj.toFixed();
console.log(a);/* w w w  .  j  a  va 2 s  .c o  m*/
a = numObj.toFixed(1);
console.log(a);
a = numObj.toFixed(6);
console.log(a);
a = (1.23e+20).toFixed(2);
console.log(a);
a = (1.23e-10).toFixed(2);
console.log(a);
a = 2.34.toFixed(1);
console.log(a);
a = 2.35.toFixed(1);
console.log(a);
a = 2.55.toFixed(1);
console.log(a);
a = -2.34.toFixed(1);
console.log(a);
a = (-2.34).toFixed(1);
console.log(a);



PreviousNext

Related