I have retrieved a string and I extracted a decimal number from it using regex, e.g. 1.00 or 3.99. Now I wanna use these numbers for calculation. How can I convert those regex results into proper numbers so I can perform calculation? In the code below, every click should add the price to the previous total but it doesn't do the sum of numbers properly.
var SaveAfrica = {
init: function () {
this.addToBasket();
},
addToBasket: function () {
var featured = $('section.featured'),
bsktTotalSpan = $('.basket_total span.basket-qty'),
list = featured.find('ul'),
item = list.find('li');
featured.delegate('.buy-now', 'click', function (e) {
var thisElem = $(this),
qtyData = thisElem.closest('li').data('price'),
total = parseInt(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
e.preventDefault();
bsktTotalSpan.text(parseFloat(total));
console.log('The total is: total);
});
}
};
SaveAfrica.init();
The HTML where the digit is from:
<li data-price="£2.99"><a href="#" class="buy-now"><img src="someImage.jpg"开发者_JAVA技巧 alt="some image" /></a></li>
Many thanks
Your problem may be that .match()
returns an array of matches. So you might try something like:
parseFloat(qtyData.match(/[\d\.\d]+/i)[0]);
What does the sum come out to, if anything at all?
You may want to try the following instead:
total = parseFloat(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
That is, parse both of them to floats And explicitly define total as a float. Otherwise, the decimals might be getting truncated somewhere.
I think there is a typo in while getting the price from the element.
The code should be as below,
qtyData = thisElem.closest('li').data('data-price'),
You can simply multiply the string by 1 in order to convert it into a number:
num = '1.00' * 1 //result is the number 1
精彩评论