JavaScript function to add two numbers is not work

2020-01-20 08:56发布

问题:

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;
}

回答1:

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



回答2:

Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.



回答3:

It's because it's treating the values as a string.

form.resistance.value + Rchange are both strings, so it's appending it.

Use the parseInt JavaScript method to get the decimal version.