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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
WordPress plugin development: How to fix a SQL injection?WordPressHow to detect the Blog Page in WordPress?WordPressControl rendering using CSS content-visibility propertyCSSWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryReview an intentionally vulnerable plugin in WordPressWordPress12 URLSearchParams methods in JavaScriptJavaScript