将 JS 计数器限制为两位小数
Restrict JS Counter to Two Number Decimals
我有一个运行良好的 JS 计数器,但我想将它限制为小数点后两位数。现在它可以高达 9。对于不会弄乱其余代码的解决方案有什么想法吗?
这是一个包含我的代码的 JSFiddle,也列在下面:https://jsfiddle.net/nd252525/26pvd7g3/3/
var INTERVAL_FIRST = 1;
var INCREMENT_FIRST = 0.86;
var START_VALUE_FIRST = 12574343;
var COUNT_FIRST = 0;
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST);
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST);",
msInterval2
);
};
function addCommas(nStr) {
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "" + "," + "");
}
return x1 + x2;
}
非常感谢任何帮助,谢谢:)
您可以将 .toFixed(2) 方法应用于您的 COUNT_FIRST
变量,以将其限制为小数点后 2 位数字。
您的代码将如下所示:
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
// Add one here
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST.toFixed(2));
// And one more here
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST.toFixed(2));",
msInterval2
);
};
代码已使用您提供的 JSFiddle 进行了测试。
我有一个运行良好的 JS 计数器,但我想将它限制为小数点后两位数。现在它可以高达 9。对于不会弄乱其余代码的解决方案有什么想法吗?
这是一个包含我的代码的 JSFiddle,也列在下面:https://jsfiddle.net/nd252525/26pvd7g3/3/
var INTERVAL_FIRST = 1;
var INCREMENT_FIRST = 0.86;
var START_VALUE_FIRST = 12574343;
var COUNT_FIRST = 0;
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST);
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST);",
msInterval2
);
};
function addCommas(nStr) {
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "" + "," + "");
}
return x1 + x2;
}
非常感谢任何帮助,谢谢:)
您可以将 .toFixed(2) 方法应用于您的 COUNT_FIRST
变量,以将其限制为小数点后 2 位数字。
您的代码将如下所示:
window.onload = function () {
var msInterval2 = INTERVAL_FIRST * 1000;
var NOW_FIRST = new Date();
COUNT_FIRST =
parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
START_VALUE_FIRST;
// Add one here
document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST.toFixed(2));
// And one more here
setInterval(
"COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST.toFixed(2));",
msInterval2
);
};
代码已使用您提供的 JSFiddle 进行了测试。