YogeshChauhan.com
How to convert a number rounding to a specified number of decimals in JavaScript?
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

dreamhost

Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?



Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?



You might also like these

How to remove border from :visited image, link or button?CSSHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?MiscHow to implement NSNumberFormatter in Swift for currency?SwiftColumn and Table Alias in PostgresPostgresMicroservices vs Monolithic ArchitectureMisc