![]() |
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: Table of Content Using the toFixed() methodIn 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.
Output 123.46 Using the Number.prototype.toPrecision() MethodIn 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.
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.
Output 123.46 2343.66 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 21 |