Incorrect result in JavaScript calculation [duplicate]

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

Leave a Comment