开发者

Get price with in string with javascript using parseFloat an parseInt not working properly

开发者 https://www.devze.com 2023-04-12 08:35 出处:网络
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 numb

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="&pound;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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号