Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...