简体   繁体   English

计算价格的%折扣。 使用Javascript

[英]Calculate % discount of price. Javascript

Trying to build a Javascript %age Discount calculator for my webshop. 试图为我的网上商店构建一个Javascript%age折扣计算器。 The problem is that the calculator calculates some products wrong by 2-10%. 问题是计算器计算出的某些产品错误率为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. 我最初使用parseFloat的建议是假设您的价格包含小数部分。 As I see now, they are in fact integers, so parseInt works fine. 正如我现在所看到的,它们实际上是整数,因此parseInt可以正常工作。

The actual issue is your replace() call isn't removing anything. 实际的问题是您的replace()调用没有删除任何内容。 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. 给你正则表达式(所以它不会被删除),并使用parseFloat而不是parseInt。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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