我在几天前发布了这段代码,但讨论似乎对Javascript的弱点(更不用说我自己作为“程序员”的明显弱点)充满了哲理,然后在没有澄清解决方案的情况下消失了。我希望有人能帮助纠正这个问题。
由于显然称为“浮点数学”的现象,Javascript在下面的计算器代码中返回算术上不准确的答案(.00000004或类似于正确答案的下方)。我被建议通过“在变量上调用math.round()”来回答这个问题,“我认为这对我的目的来说很好,只有我的JS功夫太弱了,而且在上下文中这样做的语法也是如此我没想到。
我在哪里/如何打这个电话?到目前为止,我的所有尝试都失败了,即使我确信每个人都不会。我肯定会欣赏一个考虑到我对该主题的低级知识的答案。对于那里的人来说,这必须是一个扣篮。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="javascript">
<!-- Begin Trip Tickets Savings Calc script
function doMath4() {
var one = parseInt(document.theForm4.elements[0].value);
var two = parseInt(document.theForm4.elements[1].value);
var selection = document.getElementsByName("zonett")[0].value;
if(selection == "z4"){
var prodZ4tt = (((one * two) * 4.25) *12) - (((one * two) * 3.75) *12);
alert("Your yearly savings if you buy Trip Tickets is $" + prodZ4tt + ".");
}
else if(selection == "z3"){
var prodZ3tt = (((one * two) * 3.75) *12) - (((one * two) * 3.35) *12);
alert("Your yearly savings if you buy Trip Tickets is $" + prodZ3tt + ".");
}
else if(selection == "z2"){
var prodZ2tt = (((one * two) * 3) *12) - (((one * two) * 2.8) *12);
alert("Your yearly savings if you buy Trip Tickets is $" + prodZ2tt + ".");
}
else if(selection == "z1"){
var prodZ1tt = (((one * two) * 2.5) *12) - (((one * two) * 2.3) *12);
alert("Your yearly savings if you buy Trip Tickets is $" + prodZ1tt + ".");
}
else if(selection == "Base"){
var prodBasett = (((one * two) * 1.5) *12) - (((one * two) * 1.5) *12);
alert("Your yearly savings if you buy Trip Tickets is $" + prodBasett + ".");
}
}
// End Trip Tickets Savings Calc script -->
</script>
</head>
<body>
<form name="theForm4" class="calcform">
<h2>You Do the Math: Commuter Express Trip Tickets Vs. Cash</h2>
<div class="calcform-content">
<div class="formrow-calc">
<div class="calcform-col1">
<p>Days you commute on Commuter Express monthly:</p>
</div>
<div class="calcform-col2">
<input type="text">
</div>
<div class="calcform-col3"> </div>
</div>
<div class="clear"></div>
<div class="formrow-calc">
<div class="calcform-col1">
<p>Daily boardings on Commuter Express Bus:</p>
<table border="0" cellspacing="0" cellpadding="0" class="fareexampletable">
<tr>
<td colspan="2" class="savingsleft"><p class="ifyouride">EXAMPLE:</p></td>
</tr>
<tr>
<td class="savingsleft"><p><strong>Go to work:</strong></p></td>
<td class="savingsright"><p>1 time</p></td>
</tr>
<tr>
<td class="savingsleft"><p><strong>Come home from work:</strong></p></td>
<td class="additionline savingsright"><p>+1 time</p></td>
</tr>
<tr>
<td class="savingsleft"><p><strong>Total:</strong></p></td>
<td class="savingsright"><p>2 times</p></td>
</tr>
</table>
</div>
<div class="calcform-col2">
<input type="text">
</div>
<div class="calcform-col3"> </div>
</div>
<div class="clear"></div>
<div class="formrow-calc savings-zone">
<div class="calcform-col1">
<p>Choose Zone:</p>
</div>
<div class="calcform-col2">
<select name="zonett">
<option value="Base">Base</option>
<option value="z1">Zone 1</option>
<option value="z2">Zone 2</option>
<option value="z3">Zone 3</option>
<option value="z4">Zone 4</option>
</select>
</div>
</div>
<div class="formrow-calc">
<div class="calcform-col4-ce">
<button type="submit" onclick="doMath4()" class="btn-submit"><div class="btn-submit"><img src="img/btn_savings.png" alt="Show My Yearly Savings" /></div></button>
</div>
</div>
<div class="clear">
</div>
</div>
</form>
</body>
</html>
答案 0 :(得分:2)
一般来说,你想要最后一次,所以你要保持数学准确度,直到显示数据为止。
以下是我将如何实现您的小型库:
var SavingsLib = {
round : function(val, digits) {
var pow = Math.pow(10, digits);
return Math.round(pow * val) / pow;
},
padCurrency : function (val) {
var str = val.toString();
var parts = str.split(".");
return parts.length > 1 && parts[1].length == 1 ? str + "0" : str;
},
processForm : function() {
var daysPerMonth = parseInt(document.theForm4.elements[0].value);
var boardingsPerDay = parseInt(document.theForm4.elements[1].value);
var zone = document.getElementsByName("zonett")[0].value;
var savings = 0;
if(zone == "z4") savings = this.calculateSavings(daysPerMonth, boardingsPerDay, 4.25, 3.75);
else if(zone == "z3") savings = this.calculateSavings(daysPerMonth, boardingsPerDay, 3.75, 3.35);
else if(zone == "z2") savings = this.calculateSavings(daysPerMonth, boardingsPerDay, 3, 2.8);
else if(zone == "z1") savings = this.calculateSavings(daysPerMonth, boardingsPerDay, 2.5, 2.3);
else if(zone == "Base") savings = this.calculateSavings(daysPerMonth, boardingsPerDay, 1.5, 1.5);
this.showMessage(savings);
return false; // Don't submit form
},
calculateSavings : function(daysPerMonth, boardingsPerDay, price1, price2) {
var amount1 = (((daysPerMonth * boardingsPerDay) * price1) * 12);
var amount2 = (((daysPerMonth * boardingsPerDay) * price2) * 12);
return this.round(amount1 - amount2, 2);
},
showMessage : function(savings) {
alert("Your yearly savings if you buy Trip Tickets is $" + this.padCurrency(savings));
}
}
我的更改:
1.4500001
变为1.45
而不是1
)1.4
变为1.40
)答案 1 :(得分:1)
这是very simple:
var prodZ4tt = Math.round(((one * two) * 4.25) *12) - (((one * two) * 3.75) *12);
虽然可以理解为什么你可能会对语法感到困惑,因为JavaScript并不以其直观的做事方式而闻名。 ;)
注意:这会将数字舍入到最接近的整数,但不会“向上舍入”。
答案 2 :(得分:1)
你可以用Math.round编写一个kludge,但这将会分钱(不确定这是否适用于你的例子,看起来有点像)。你可能想要的是修复:
alert((102.000000004).toFixed(2)); // alerts "102.00"
这在IE中并不圆,但从我所知道的情况来看,这对你的情况无关紧要。
(文档:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed,http://www.codingforums.com/showthread.php?t=102421,http://msdn.microsoft.com/en-us/library/sstyff0z.aspx)
编辑:打算把它放在评论中,但降价在那里不起作用?还是习惯了......
无论如何,如果您愿意,也可以使用带有Math.round的kludge:
alert(Math.round(val * 100) / 100);
哪些可能仍会显示愚蠢的浮动问题,你可以使用另一个.toFixed(现在你100%确定没有剩余的小数位,你没有正确地舍入):
alert((Math.round(val * 100) / 100).toFixed(2));
编辑:整合:
在脚本块的顶部添加:
function roundNicely(val) {
return (Math.round(val * 100) / 100).toFixed(2);
}
然后在警报中,将值prodBasett
包装在函数调用中:roundNicely(prodBasett)
(和其他警报类似)
这有意义吗?
答案 3 :(得分:1)
对于需要精确度的情况,你必须要一个数学“任意精度库”......你可以在这里找到一篇好文章。
http://blog.thatscaptaintoyou.com/introducing-big-js-arbitrary-precision-math-for-javascript/
Javascript本身具有round,ceil和floor来将浮点数转换为整数。
var fl = 349.12783691847;
Math.round(fl) // 349
Math.ceil(f1) // 350
Math.floor(fl) // 349
当你做数学运算时,好的做法是使用分配,并正确使用括号。
Math.round(((((a + b) * (c - d)) % e) * f));
小心使用“NaN”(http://en.wikipedia.org/wiki/NaN)和非数字类型。
度过愉快的一天