Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

html - JavaScript function to add two numbers is not working right

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.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...