We can use toFixed() method to do so.

JavaScript toFixed() Method

This method performs two operations. It converts a number into a string as well as rounds the number to keep to specified decimals.

If the desired number of decimals are higher than the actual number, zeros are added to create the desired decimal length.

This method is supported by all major browsers.

Syntax


number.toFixed(x)

where x is optional. It is used to specify the number of digits after the decimal point. Default is 0 (no digits after the decimal point)

Examples


function convertTo2decimals(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(convertTo2decimals(111.111));
console.log(convertTo2decimals(0.001));
console.log(convertTo2decimals('1.11e+5'));

//Output
111.11
0.00
111000.00

function convertTo3decimals(x) {
  return Number.parseFloat(x).toFixed(3);
}

console.log(convertTo3decimals(111.111));
console.log(convertTo3decimals(0.001));
console.log(convertTo3decimals('1.11e+5'));

// output
111.111
0.001
111000.000

RangeError

If digits is too small or too large. Values between 0 and 100, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as chosen.

TypeError

If this method is invoked on an object that is not a Number.

Read more on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

0 Comments

Leave a reply

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