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.



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)


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



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


// output


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.


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

Credit: MDN Docs

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a vertically rotating texts using CSS?CSSHow to change style of all direct children of an element using jQuery?jQueryHow to clean up after a plugin uninstall in WordPress?WordPressWindow innerHeight and innerWidth properties in JavaScriptJavaScriptHow to create ‘share on LinkedIn’ link using just HTML?HTMLWordPress: How to create a folder if it doesn’t already exist?WordPress