javascriptjquerycalculation

Concatenating mathematical formula with dollar sign


With jQuery, I'm doing some math to calculate a price. The math works, but I want to put a dollar sign in front of it, and when I try adding "$" + into the code, the math stops working correctly. How can I get the value of #totalprice to include the dollar sign?

$('#totalprice').val("$" + $('#qty1').val() * $('#price1').val() + $('#qty2').val() * $('#price2').val());

Solution

  • Assuming in your example that .val() is returning a number, consider what JavaScript would do with that number when you do this:

    "$" + $('#qty1').val()
    

    The value "$" isn't a number. (After all, what would $ + 5 equal?) It's a string. So JavaScript coerces the number value into a string and concatenates.

    Basically the + operator means something different with strings than it does with numbers.

    Perform your logic in two distinct steps. First use the numbers to calculate a result, then concatenate that result into an output string. You can do this on the same line of code by grouping your mathematical expression with parentheses. For example:

    "$" + ($('#qty1').val() * $('#price1').val() + $('#qty2').val() * $('#price2').val())