我的HTML代码使用一个用户输入数字,然后进行计算,然后显示输出.用户选择的输入被放到公式中,公式的结果被添加到用户输入数字中,但是当将两个数字相加时,将添加一个小数点.
My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
例如,如果选择数字11,则Rchange的结果为0.22,因此对于newResistance,将.22加11到11.22,但是将其显示为110.22.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) { if (isNaN(form.resistance.value)) { alert("Error in input"); return false; } if (form.resistance.value.length > 32) { alert("Error in input"); return false; } var Rchange = .01 * 2 * form.resistance.value; var newResistance = (form.resistance.value + Rchange); document.getElementById("newResistance").innerHTML = chopTo4(newResistance); } function chopTo4(raw) { strRaw = raw.toString(); if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5); return strRaw; } 推荐答案HTML DOM元素属性始终是字符串.您需要在使用时将其转换为数字.
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value); parseFloat(form.resistance.value); +form.resistance.value;(三个中的任何一个都可以;我更喜欢前两个(除非您要查找浮点数,否则请使用parseInt).)
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)