Incorrect result in JavaScript calculation

点点圈 提交于 2019-12-17 14:56:50

问题


I'm fairly new to JavaScript and wanted to convert one of my calculation spreadsheets to something I can use on a web page. However, the calculation gives me an incorrect result.

Here's my JavaScript:

<script type="text/javascript" language="JavaScript">
        function calc() {
            var onerepmax = document.wodCalculate.oneRepMax.value;
            var percent = document.wodCalculate.percentOfOneRepMax.value / 100;
            var addkg = document.wodCalculate.plusKg.value;
            var zwischenschritt = onerepmax * percent;
            var gewicht = zwischenschritt + addkg;
            document.getElementById("weight").innerHTML = gewicht;
        };
</script>

and here's the HTML:

<form action="" id="wodCalculate" name="wodCalculate">
        <table cellspacing="0" cellpadding="10" border="0">
            <tr><td>1 Rep Max</td><td><input type=text name="oneRepMax" value="">&nbsp;kg<br></td></tr>
            <tr><td>% vom 1RM</td><td><input type=text name="percentOfOneRepMax" value="">&nbsp;%<br></td></tr>
            <tr><td>Plus x kg</td><td><input type=text name="plusKg" value="">&nbsp;kg<br></td></tr>
            <tr><td><input type="button" value="Calculate" onClick="calc()"></td></tr>
        </table>
</form>
<div id="weight">Weight</div>

It works fine up to the point of multiplying the "onerepmax" with the "percent". However, once it gets to the point of adding the "addkg" to the result of the multiplication (i.e. giving me the "gewicht"), the result becomes incorrect.

For example, I want to get 10% of 100kg and add 10kg. Instead of 20kg, the calculation result is 1010.

Thanks for your help!


回答1:


The value of an input is always a string, so + ends up being string concatenation ("10" + "10" is "1010", as opposed to 10 + 10 which is 20).

If you're using an input type="number" (the OP isn't, but others finding this answer may) and the browser supports them, you can use valueAsNumber instead:

var onerepmax = document.wodCalculate.oneRepMax.valueAsNumber;

If you're using type="text" or the browser doesn't support valueAsNumber:

You can convert user-input values using parseInt(value, 10) (the 10 = decimal, base 10) if they're meant to be whole numbers, e.g.:

var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);

That's just one option, though, you have several:

  • The unary + operator: value = +value will coerce the string to a number using the JavaScript engine's standard rules for that. The number can have a fractional portion (e.g., +"1.50" is 1.5). Any non-digits in the string (other than the e for scientific notation) make the result NaN. Also, +"" is 0, which may not be intuitive.

    var onerepmax = +document.wodCalculate.oneRepMax.value;
    
  • The Number function: value = Number(value). Does the same thing as +.

    var onerepmax = Number(document.wodCalculate.oneRepMax.value);
    
  • The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.

    // (Same as the first one above)
    var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);
    
  • The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.

    var onerepmax = parseFloat(document.wodCalculate.oneRepMax.value);
    

So, pick your tool to suit your use case. :-)




回答2:


The problem is that you're "adding" a string, not a number. The + operator in JavaScript has multiple semantics, and as soon as one operand is a string, it will do string concatenation.

To prevent that, convert the string to a number with the unary + operator.



来源:https://stackoverflow.com/questions/32945779/incorrect-result-in-javascript-calculation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!