6

I have used following code to add three variables but instead of adding these variables its concatenating these variables.

var registration_fee = $('input[type="radio"][name="registration_fee"]:checked').val();
var material_fee = $('input[type="radio"][name="material_fee"]:checked').val();
var tuition_fee = $('input[type="radio"][name="tuition_fee"]:checked').val();
// alert(tuition_fee)
var total_fee = registration_fee + material_fee + tuition_fee;
$('#total_fee').html(total_fee);

5 Answers 5

13

Cast them to numbers using parseInt or parseFloat:

var total_fee = parseInt(registration_fee) + parseInt(material_fee) + parseInt(tuition_fee);
Sign up to request clarification or add additional context in comments.

4 Comments

BUt if I have used ,val() whats need to parse it than?
Or if you want something more compact you can always use the unary plus operator. I'd suggest doing the conversion from string to number at the time you set the variable values, so like this: var tuition_fee = +$('input[type="radio"][name="tuition_fee"]:checked').val(); (etc.) - note the '+' before the '$'.
You should always specify the radix when using parseInt
You should always specify the radix when accepting user-typed numbers. If your system doesn't generate hex or octal numbers you'll be fine.
2

Try:


var total_fee = parseInt(registration_fee, 10) + parseInt(material_fee, 10) + parseInt(tuition_fee, 10);

Or parseFloat, whichever suits

Comments

2

Try

Cast them to numbers using Number

tal_fee = Number(registration_fee) + Number(material_fee) + Number(tuition_fee);

Comments

1

Use parseInt to turn the string to int, or parseFloat for float.

Comments

0

Try to use parseInt(price) + parseInt(ticket_buyer_fee) for the variables it works

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.