# JavaScript Format Number 2 Decimals

Last Updated : Sep 4, 2023 In this article we will show you the solution of JavaScript Format Number 2 Decimals, in this tutorial, we will use two different methods in JavaScript to format the number 2 decimal.

### toFixed() method

toFixed() method: this method is used to return any number to a specified decimal value. Syntax:

`number.toFixed(NoOfDecimal)`

### math.random() method

math.random() method: in this method, we will have a random integer. And using a function to format numbers to 2 decimal values.

And also gonna use a function of Number.EPSILON.

## Step By Step Guide On JavaScript Format Number 2 Decimals :-

### Method 1 - using toFixed() method

```<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>javascript format number 2 decimals</title>
<style>
h1 {
color : rgb(95, 194, 95) ;
font-size: 25px;
font-weight : bolder ;
}
</style>
<body>
<center>
<h1> TALKERSCODE </h1>
<h3> javascript format number 2 decimal </h3>
</center>
<script>
const num = 51.4861379871 ;
const decimal_num = num.toFixed(2) ;
console.log("formatted to 2 decimal: ", decimal_num) ;
</script>
</body>
</html>```
1. To write HTML code <! DOCTYPE html> to mention which version of the HTML file is written in.
2. Then we have to write the <html> tag used to define the root of an HTML document. And also write the ending tag </html>.
4. Then <title> tag is used to set the title of the HTML document and end it with </title> tag.
5. Attach an external CSS file using <link> tag to give style to the page
7. Create a <Script> tag to write JavaScript within it.
8. A constant num with some values a created using const
9. Using toFixed() function and set the decimal value to 2
10. Console.log() to display the formatted number upto 2 decimal

### Method 2 - using math.random()

```<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>javascript format number 2 decimals</title>
<style>
h1 {
color : rgb(95, 194, 95) ;
font-size: 25px;
font-weight : bolder ;
}
</style>
<body>
<center>
<h1> TALKERSCODE </h1>
<h3> javascript format number 2 decimal </h3>
</center>
<script>
const value = Math.random() ;
const round = (value, digits) => {
const factor = Math.pow(10, digits) ;
value += Math.sign(value) * Number.EPSILON ;
return Math.round(value*factor) / factor ;
} ;
console.log(round(value, 2)) ;
</script>
</body>
</html>```
1. To write HTML code <! DOCTYPE html> to mention which version of the HTML file is written in.
2. Then we have to write the <html> tag used to define the root of an HTML document. And also write the ending tag </html>.
4. Then <title> tag is used to set the title of the HTML document and end it with </title> tag.
5. Attach an external CSS file using <link> tag to give style to the page