-1

Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?

I have a select element that contains options for products. What I want to achieve is when they pick an option the price on the page automatically adjusts. I have figured out how to retrieve those values but when I combine them it just puts two numbers together instead of actually adding them.

For example instead of outputting 60 when I have 50 + 10 it outputs 5010.

My code:

$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');

var new_price = base_price+add_price;

console.log(new_price);

$('.current_price').html(base_price+add_price);

});

Is there a way I can convert them both to integers so the operation actually goes through?

Thanks in advance!

1
  • You can use some tricks like multiplying by 1 to force a number cast or you can use parseInt() Commented Nov 14, 2012 at 21:07

5 Answers 5

5

Use parseInt

$('.product_options').change(function(){
var base_price = parseInt($('#base_price').html(), 10); // 10 as second argument will make sure that base is 10.
var add_price = parseInt($(this).find("option:selected").data('price'), 10);

var new_price = base_price+add_price;

console.log(new_price);

$('.current_price').html(base_price+add_price);
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

var base_price = +$('#base_price').html();
var add_price = +$(this).find("option:selected").data('price');

See the mighty: Mozilla's Arithmetic Operators Reference - Unary Negation

2 Comments

I had no idea..! Does this work on all browsers?
@BillyMoon: It's part of the EMCAScript specification.
0

Any values you pull out of the DOM are going to be strings, and need converting into number types before you can do mathematical operations with them.

parseInt( ... ) is a built in javascript function that converts a string into an integer, if the string consists of digits only.

If you need a decimal number, you can use parseFlaot.

var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`

Comments

0

Use parseFloat or parseInt

$('.product_options').change(function(){
  var base_price = $('#base_price').html();
  var add_price = $(this).find("option:selected").data('price');

  var new_price = parseFloat(base_price) + parseFloat(add_price);

  console.log(new_price);

  $('.current_price').html(base_price+add_price);
});

Comments

0

Yes there is.

intval = parseInt(string)

is what you're looking for.

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.