简体   繁体   中英

Calculate % discount of price. Javascript

Trying to build a Javascript %age Discount calculator for my webshop. The problem is that the calculator calculates some products wrong by 2-10%. Please help, whats wrong in the code?

<script type="text/javascript">

$(document).ready(function() {

/*
Least allowed discount to show.
*/
var minDiscount = 15;



$('.gridArticlePrices').each(function() {
    /* Get ordinary price */
    var oldPrice = $(this).children('.gridArticlePriceRegular').html();
    /* Get sale price */
    var newPrice = $(this).children('.gridArticlePrice').children('.reducedPrice').html();

    if ((oldPrice) && (newPrice)) {
        /* Convert to numbers instead of strings */
        var oldPrice = parseInt(oldPrice.replace("/[^0-9]/g", ""));
        var newPrice = parseInt(newPrice.replace("/[^0-9]/g", ""));

        /* Calcuate the precentage, rounded of to 0 decimals */
        var discount = Math.round(100 - ((newPrice / oldPrice) * 100));

        /* If the precentage is higher than "var min Discount" then write out the discount next to the products price.*/
        if (discount >= minDiscount) {
            $(this).parent().after("<div class='discount'>-" + discount + "%</div>");
        }
    }
});

});

</script>

UPDATE:

My original suggestion to use parseFloat was assuming your prices included decimal components. As I see now, they are in fact integers, so parseInt works fine.

The actual issue is your replace() call isn't removing anything. You should remove the quotes around the regex, and then it will remove the extra characters you don't want.

var oldPrice = parseInt(oldPrice.replace(/[^0-9]/g, ""));
var newPrice = parseInt(newPrice.replace(/[^0-9]/g, ""));

Note: If you do need to handle decimal prices, you would need to add "." to you regex (so it doesn't get removed), and use parseFloat instead of parseInt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM