复杂数学计算中的四舍五入小数
Round Decimals Within Complex Math Calculation
我一直在处理一个变量,但我似乎无法按照我希望的方式输出它。这是我目前拥有的变量:
var resource1RatePerHour = Math.ceil(resource1BaseRate1 * Math.pow(resourceIncomeModifier, resource1BuildingLevel) +30) / 3600;
现在每秒在增量计时器上调用一次,但必须计算为每小时增益(因此除以 3600)。
这一切似乎都有效,但我的问题是现在有许多我想删除的尾随数字,最好不要使用 trim 方法。之前(使用 Math.ceil)我不会得到任何小数。如果我在 Math.ceil 等式中添加“/ 3600”,整个计算将无法进行,因此它必须位于 Math.ceil 和 Math.pow.
之外
如果你只是想以一种漂亮的格式显示它,我认为转换为字符串会删除它们。
var x = 1.245000
var niceDisplay = x.toString() // "1.245"
您可以使用JavaScript toFixed()
函数:
var x = 123.45 * 234.56;
document.body.innerHTML += x.toFixed(0) + "<br/>";
document.body.innerHTML += x.toFixed(1) + "<br/>";
document.body.innerHTML += x.toFixed(2) + "<br/>";
document.body.innerHTML += x.toFixed(3) + "<br/>";
document.body.innerHTML += x.toFixed(4) + "<br/>";
document.body.innerHTML += x.toFixed(5) + "<br/>";
我一直在处理一个变量,但我似乎无法按照我希望的方式输出它。这是我目前拥有的变量:
var resource1RatePerHour = Math.ceil(resource1BaseRate1 * Math.pow(resourceIncomeModifier, resource1BuildingLevel) +30) / 3600;
现在每秒在增量计时器上调用一次,但必须计算为每小时增益(因此除以 3600)。
这一切似乎都有效,但我的问题是现在有许多我想删除的尾随数字,最好不要使用 trim 方法。之前(使用 Math.ceil)我不会得到任何小数。如果我在 Math.ceil 等式中添加“/ 3600”,整个计算将无法进行,因此它必须位于 Math.ceil 和 Math.pow.
之外如果你只是想以一种漂亮的格式显示它,我认为转换为字符串会删除它们。
var x = 1.245000
var niceDisplay = x.toString() // "1.245"
您可以使用JavaScript toFixed()
函数:
var x = 123.45 * 234.56;
document.body.innerHTML += x.toFixed(0) + "<br/>";
document.body.innerHTML += x.toFixed(1) + "<br/>";
document.body.innerHTML += x.toFixed(2) + "<br/>";
document.body.innerHTML += x.toFixed(3) + "<br/>";
document.body.innerHTML += x.toFixed(4) + "<br/>";
document.body.innerHTML += x.toFixed(5) + "<br/>";