Home  >  Article  >  Web Front-end  >  What is the way to keep two decimal places in javascript

What is the way to keep two decimal places in javascript

WBOY
WBOYOriginal
2022-01-19 16:49:586630browse

In JavaScript, you can use the toFixed() method to retain two decimal places. The function of this method is to round the value to a number with specified decimal places. When the parameter is set to "2", the result returned Two decimal places of the specified value will be retained, and the syntax is "value.toFixed(2)".

What is the way to keep two decimal places in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What is the method to retain two decimal places in JavaScript

The toFixed() method can round Number to a number with specified decimal places.

The syntax is:

number.toFixed(x)

where x is required. Specifies the number of decimal places, which is a value between 0 and 20, inclusive. Some implementations can support a larger range of values. If this parameter is omitted, 0 will be used instead.​

The returned result has a fixed number of x digits after the decimal point.

The example is as follows:

<html>
<head>
<meta charset="utf-8">
<title>123</title>
</head>
<body>
<p id="demo">单击按钮显示保留小数的数值</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var num = 5.56789;
var x = document.getElementById("demo");
x.innerHTML=num.toFixed(2);
}
</script>
</body>
</html>

Output result:

What is the way to keep two decimal places in javascript

##Related recommendations:

javascript learning tutorial

The above is the detailed content of What is the way to keep two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn