Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading