[英]Calculate % discount of price. Javascript
試圖為我的網上商店構建一個Javascript%age折扣計算器。 問題是計算器計算出的某些產品錯誤率為2-10%。 請幫忙,代碼有什么問題?
<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>
更新:
我最初使用parseFloat的建議是假設您的價格包含小數部分。 正如我現在所看到的,它們實際上是整數,因此parseInt可以正常工作。
實際的問題是您的replace()調用沒有刪除任何內容。 您應該刪除正則表達式周圍的引號,然后它將刪除不需要的多余字符。
var oldPrice = parseInt(oldPrice.replace(/[^0-9]/g, ""));
var newPrice = parseInt(newPrice.replace(/[^0-9]/g, ""));
注意:如果確實需要處理小數價格,則需要添加“。” 給你正則表達式(所以它不會被刪除),並使用parseFloat而不是parseInt。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.