-1

可能重复:
如何在 JavaScript 中将字符串转换为整数?

我有一个包含产品选项的选择元素。我想要实现的是,当他们选择一个选项时,页面上的价格会自动调整。我已经想出了如何检索这些值,但是当我将它们组合起来时,它只是将两个数字放在一起,而不是实际添加它们。

例如,当我有 50 + 10 时,它不是输出 60,而是输出 5010。

我的代码:

$('.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);

});

有没有办法可以将它们都转换为整数,以便操作实际进行?

提前致谢!

4

5 回答 5

5

利用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);
});
于 2012-11-14T21:07:18.250 回答
1

尝试:

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

查看强大的:Mozilla 的算术运算符参考 - 一元否定

于 2012-11-14T21:07:52.940 回答
0

就在这里。

intval = parseInt(string)

就是你要找的。

于 2012-11-14T21:10:08.643 回答
0

您从 DOM 中提取的任何值都将是字符串,并且需要转换为数字类型才能对它们进行数学运算。

parseInt( ... )是一个内置的 javascript 函数,如果字符串仅包含数字,则将字符串转换为整数。

如果需要十进制数,可以使用parseFlaot.

var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`
于 2012-11-14T21:08:40.457 回答
0

使用 parseFloat 或 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);
});
于 2012-11-14T21:09:27.323 回答