Yogesh Chauhan's Blog

How to convert a number rounding to a specified number of decimals in JavaScript?

in JavaScript on November 12, 2020

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.

Credit: MDN Docs


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to create a Recent Posts function in WordPress?WordPress12 URLSearchParams methods in JavaScriptJavaScripttransform-origin Property in CSSCSSWhat does Containment mean in React?ReactResponsive Masonry Grid using CSS columns PropertyCSSKilling A Project Part 1: What criteria should be used to cancel/kill a project?Miscellaneous