Skip to content Skip to sidebar Skip to footer

Javascript Math Different To What I Thought It Should Be

Just wondering if someone knows what is wrong with my javascript math script below: var new_total = (document.getElementById('qty').value * document.getElementById('pricepermetre')

Solution 1:

document.getElementById('delivery').value returns a string, and you'll end with string concatenation since + is used by JS to concat string.

update

JavaScript's + has different meaning depending on what you use. Amazingly, * can multiply even if the number is shown as string.

try this

// `*` will infer that you wanted multiplication
alert("2" * 2);
alert("2" * 2);
alert(2 * "2");
alert(2 * 2);

// however, the `+` may take addition or string concatenation
alert("1" + "0");
alert("1" + 0);
alert(1 + "0");
alert(1 + 0);

sample code


Solution 2:

The value property of elements that have it (input elements and the like) is a string. Now, JavaScript will try to do what you want by converting the string to a number intrinsically, but it can't guess at your intent, and specifically when one side of the + operator is a number and the other side is a string, the engine will assume you want to convert the number to a string and concatenate, rather than assuming you want to convert the other string to a number and add.

To properly convert a string to a number, use parseInt (and specify the radix) for whole numbers or parseFloat for fractional numbers expressed in decimal. So if these are whole numbers:

var new_total = (
      parseInt(document.getElementById('qty').value, 10) *
      parseInt(document.getElementById('pricepermetre').value, 10)
    ) +
    parseInt(document.getElementById('delivery').value, 10);

Or if they're decimals:

var new_total = (
      parseFloat(document.getElementById('qty').value) *
      parseFloat(document.getElementById('pricepermetre').value)
    ) +
    parseFloat(document.getElementById('delivery').value);

Note that there's no radix parameter on parseFloat; the number is always expected to be in base 10 decimal.

Relying on JavaScript's rules for when it should "coerce" strings to numbers is usually a bad idea, not least because you need to be sure to control the radix and such.


Solution 3:

Try using parseInt(document.getElementById('delivery').value). You've got a problem with casting (or type inference, whatever).


Solution 4:

The JavaScript engine is confusing strings and numbers, try:

var new_total = (document.getElementById('qty').value) * document.getElementById('pricepermetre').value) + parseInt(document.getElementById('delivery').value);


Solution 5:

Maybe this does the job

var new_total = parseInt((document.getElementById('qty').value * document.getElementById('pricepermetre').value)) + parseInt(document.getElementById('delivery').value)

Post a Comment for "Javascript Math Different To What I Thought It Should Be"