Horje
How to Format a Number with Two Decimals in JavaScript?

In javascript, formatting numbers to a fixed number of decimal places is a common requirement, particularly in financial calculations, statistical data presentations, and to show in user interfaces. In this article we will explore different approaches to format a number with two decimals in JavaScript.

Below are different approaches to format a number with two decimals in JavaScript:

Using the toFixed() method

In this approach we are using the toFixed() method. This method formats a number using fixed-point notation. It converts the number to a string and keep a specified number of decimals.

Syntax:

number.toFixed(digits)

Where:

digits is the number of digits to appear after the decimal point.

Example: In below example we are using the toFixed() method to format a number with two decimals.

JavaScript
let num = 123.4564;
let formattedNum = num.toFixed(2);
console.log(formattedNum); 

Output
123.46

Using the Number.prototype.toPrecision() Method

In this approach we are using the toPrecision() method. This method formats a number to a specified precision (total number of significant digits).

Syntax:

number.toPrecision(precision)

Where:

precision is an integer specifying the number of significant digits.

Example: In below example we are using the toPrecision() Method to format a number with two decimals.

JavaScript
let num = 5438.876;
let formattedNum = num.toPrecision(6);
console.log(formattedNum);

Output
5438.88

Using Mathematical Rounding with Math.round()

In this approach we have used the Math.round() method. It rounds a number to the nearest integer. To round a number to two decimal places we can manipulate the number before and after using Math.round(). By multiplying the number by 100, rounding it, and then dividing by 100, we effectively round the number to two decimal places.

Syntax:

Math.round((number + Number.EPSILON) * 100) / 100

Example: In below example we are using the Math.round() method to format a number with two decimals.

JavaScript
let num1 = 123.456789;
let formattedNum1 = Math.round((num1 + Number.EPSILON) * 100) / 100;
console.log(formattedNum1);

let num2 = 2343.657321;
let formattedNum2 = Math.round((num2 + Number.EPSILON) * 100) / 100;
console.log(formattedNum2);

Output
123.46
2343.66



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Get Cookie by Name in JavaScript? How to Get Cookie by Name in JavaScript?
How to Format Date with Moment.js? How to Format Date with Moment.js?
What Happened to Lodash _.pluck? What Happened to Lodash _.pluck?
How to Change Language in MomentJS? How to Change Language in MomentJS?
How to Deep Merge Two Objects in JavaScript ? How to Deep Merge Two Objects in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
21