JavaScript 浮点数精度
JavaScript中浮点数的表示遵循IEEE-754格式。它是一种双精度格式,在每个浮点数上分配了64位。这些浮动值的显示可以使用2种方法来处理:
使用 toFixed()方法: 可以使用toFixed()方法设置浮点值的小数位数。此方法将数字转换为字符串,保留指定小数点后的位数。如果没有传递参数作为值,则取0作为默认值,即不显示小数点。
语法:
number.toFixed(digits)
示例:
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Floating point number precision
in JavaScript?
</b>
<p>
Original floating point: 3.14159265359
</p>
<p>
Floating point when decimal places set
to 2: <span class="output-2"></span>
</p>
<p>
Floating point when decimal places set
to 5: <span class="output-5"></span>
</p>
<button onclick="setDecimalPlaces()">
Change decimal points
</button>
<script type="text/javascript">
function setDecimalPlaces() {
pi = 3.14159265359;
twoPlaces = pi.toFixed(2);
fivePlaces = pi.toFixed(5);
document.querySelector('.output-2').textContent
= twoPlaces;
document.querySelector('.output-5').textContent
= fivePlaces;
}
</script>
输出:
使用 toPrecision() 方法:
toPrecision() 方法可以设置浮点数值中的总数字位数。该方法将数字转换为一个字符串,并根据指定的总数字位数对其进行四舍五入。如果没有传入参数,则该方法将起到 toString() 函数的作用,将数值转换为字符串并返回。
语法:
number.toPrecision(precision)
示例:
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Floating point number precision
in JavaScript?
</b>
<p>
Original floating point: 3.14159265359
</p>
<p>
Floating point when precision set to
2: <span class="output-2"></span>
</p>
<p>
Floating point when precision set to
5: <span class="output-5"></span>
</p>
<button onclick="setPrecision()">
Click to check
</button>
<script type="text/javascript">
function setPrecision() {
pi = 3.14159265359;
twoPlaces = pi.toPrecision(2);
fivePlaces = pi.toPrecision(5);
document.querySelector('.output-2').textContent
= twoPlaces;
document.querySelector('.output-5').textContent
= fivePlaces;
}
</script>
输出: