将变量舍入为1个十进制javascript

Round variable to 1 decimal javascript

本文关键字:十进制 javascript 1个 变量 舍入      更新时间:2023-09-26

我有一个litte脚本,每秒添加0.2。它显示15个小数,但我只想要1。我如何在JavaScript中做到这一点?我自己试过,但做不到。

到目前为止,我得到的是:https://jsfiddle.net/0qhx7s4t/

var doughnut = 0;
show_value();
setInterval(function(){
    doughnut += 0.2;
    show_value();
}, 1000);
function show_value(){
    document.getElementById("co").innerHTML = doughnut;
}
<li><label id="co"></label> CO&#178;</li>

您可以使用toFixed方法:

var doughnut = 0;
show_value();
setInterval(function(){
    doughnut += 0.2;
    show_value();
}, 1000);
function show_value(){
    document.getElementById("co").innerHTML = doughnut.toFixed(1);
}
<li><label id="co"></label> CO&#178;</li>

您可以使用.toFixed(1)

var doughnut = 0;
show_value();
setInterval(function(){
    doughnut += 0.2;
    show_value();
}, 1000);
function show_value(){
    document.getElementById("co").innerHTML = doughnut.toFixed(1);
}
<li><label id="co"></label> CO&#178;</li>

使用Math.round(num * 10) / 10:https://jsfiddle.net/0qhx7s4t/1/