简体   繁体   English

复杂数学计算中的舍入小数

[英]Round Decimals Within Complex Math Calculation

I have a variable I've been working on which I can't seem to output the way I would like it to. 我有一个正在处理的变量,我似乎无法按照自己的意愿输出。 Here is the variable I currently have: 这是我当前拥有的变量:

var resource1RatePerHour = Math.ceil(resource1BaseRate1 * Math.pow(resourceIncomeModifier, resource1BuildingLevel) +30) / 3600;

Now this is called on a increment timer every second, though has to be calculated as a per hourly gain (hence the division by 3600). 现在,虽然必须将其计算为每小时增益(因此除以3600),但每秒需要在增量计时器上调用一次。

This all seems to work however my issue is that there are now many trailing digits which I would like removed, preferably not using a trim method. 这一切似乎都起作用,但是我的问题是,现在我想删除许多尾随数字,最好不要使用修剪方法。 Before (using Math.ceil) I wouldn't get any decimals. 以前(使用Math.ceil)我不会得到任何小数。 If I add the "/ 3600" within the Math.ceil equation the whole calculation will not work, so it has to stay outside both Math.ceil and Math.pow. 如果在Math.ceil方程式中添加“ / 3600”,则整个计算将无法进行,因此它必须位于Math.ceil和Math.pow之外。

If you just want to display it in a nice format, converting to a string will remove them I think. 如果您只想以一种不错的格式显示它,则转换为字符串会删除它们。

var x = 1.245000
var niceDisplay = x.toString() // "1.245" 

You can use JavaScript toFixed() function: 您可以使用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/>"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM