YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Introduction to Angular modules Part 1: NgModule metadataAngular2 Ways we can create an Array in JavaScriptJavaScriptWordPress: How to display fields from ACF Flexible Contents?WordPressAll possible ways you can Insert Data in PostgresPostgresAngular: Templates, directives, data binding, Services and dependency injectionAngularHow to set the permissions on all files and folders in Mac?Misc