如何使用 Javascript 获得精确到便士的购物车结账价格?
如何使用 Javascript 获得精确到便士的购物车结账价格?
现在,在进行了所有的试用轮等之后,我正在尝试。使用 15 种高产品/价格进行测试,我的价格上涨了 1.5 美分。
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将为您提供值,但它将是一个字符串。如果您需要它保持数字,请使用:
that will give you the value, but it will be a string. If you need it to stay numeric, use:
您需要对每个订单项的折扣进行四舍五入:
priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
请注意,如果您添加未四舍五入的结果,然后四舍五入,则此结果可能与您得到的结果不一致。和。但是,这是手动计算发票时通常的工作方式(特别是因为每个项目可以有不同的折扣百分比,所以折扣是针对每行计算的)。
我认为您遗漏了一行内容:
discountAmount += PriceDiscount
。You need to round the discount for each line item:
priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying
discountAmount += priceDiscount
.将您的代码修改为:
和:
modify your code to :
and: