如何在Javascript中对代码行进行舍入?

时间:2016-02-15 17:26:41

标签: javascript

这不是单行代码。 如何在Javascript中对代码行进行舍入? 如何将其四舍五入到小数点?



 if (aSelectedValue >= bSelectedValue) {
				document.getElementById("Answer").innerHTML = "0€";
				document.getElementById("Answer").innerHTML = "Debug3";
			}	else if (bSelectedValue <= 1600) { 

					document.getElementById("Answer").innerHTML = (+bSelectedValue - +aSelectedValue) * 0.075 + "€";
					
			}	else if (bSelectedValue <= 1900 && bSelectedValue >=1600 && aSelectedValue < 1900 && aSelectedValue >= 1600) {
				
					document.getElementById("Answer").innerHTML = (+bSelectedValue - +aSelectedValue) * 0.15 + "€";
				
			}	else if (bSelectedValue <= 2500 && bSelectedValue >=1900 && aSelectedValue <= 2500 && aSelectedValue >= 1900) {
			
					document.getElementById("Answer").innerHTML = (+bSelectedValue - +aSelectedValue) * 0.5 + "€";
					
			}	else if (aSelectedValue >= 1300 && aSelectedValue <= 1600 && bSelectedValue <= 1900) {
				
					document.getElementById("Answer").innerHTML = (1600 - +aSelectedValue) * 0.075 + (+bSelectedValue - 1600) * 0.15 + "€";
					
			}	else if (aSelectedValue > 1600 && aSelectedValue <= 1900 && bSelectedValue <= 2500) {
					
					document.getElementById("Answer").innerHTML = (1900 - +aSelectedValue) * 0.15 + (+bSelectedValue - 1900) * 0.5 + "€";
					
			}	else if (bSelectedValue <= 2500) {
				
				document.getElementById("Answer").innerHTML = (1600 - +aSelectedValue) * 0.075 + (+bSelectedValue - 1900) * 0.5 + 45 + "€";
				
			}

   
&#13;
&#13;
&#13;

这是完整的

1 个答案:

答案 0 :(得分:0)

也许这个?

var number = (1600 - +aSelectedValue) * 0.075 + (+bSelectedValue - 1600) * 0.15;
number = +number.toFixed(2);
document.getElementById("Answer").innerHTML = number + "€";

或者也许使用这样的函数:

function roundNum(number,amount){//amount is the rounding value, in this case, 2
    return +number.toFixed(amount);
}
roundNum(yournumber,2);

这允许您围绕每行代码注意: 虽然您可以简单地使用toFixed(),但这可能会导致数字舍入不正确的问题,因此添加+的问题很少。