-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!

Community
  • 1
  • 1
user1701398
  • 1,649
  • 3
  • 15
  • 16
  • You can use some tricks like multiplying by 1 to force a number cast or you can use parseInt() – TheZ Nov 14 '12 at 21:07

5 Answers5

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);
});
Anoop
  • 23,044
  • 10
  • 62
  • 76
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

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
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`
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
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);
});
0

Yes there is.

intval = parseInt(string)

is what you're looking for.

Silvester
  • 496
  • 1
  • 3
  • 14