Magento 2 Minicart / Knockout.js:格式计算价格/总和

问题描述 投票:0回答:1

在 Magento 2 minicart (CE 2.4.6) 中,我不仅想显示购物车中每件商品的价格,还想显示每件商品的总和(如果购物车中同一商品有多个单位)。因此,我将以下行添加到 minicart/item/default.html:

<span class="price" data-bind="text: (item.qty * item.product_price_value)"></span>

输出格式如下:89.6999999999999

我需要带有逗号分隔符和两位小数的欧洲格式。所以我尝试了:

<span class="price" data-bind="text: (item.qty * item.product_price_value).toFixed(2)."></span>

这适用于小数:89.70

然后我尝试了:

<span class="price" data-bind="text: (item.qty * item.product_price_value).toLocaleString('de-DE')"></span>

这适用于逗号:89,6999999999999

但是,我找不到同时实现逗号和小数位数的方法。

<span class="price" data-bind="text: (item.qty * item.product_price_value).toFixed(2).toLocaleString('de-DE')"></span>

这再次仅显示正确的小数,但分隔符错误。

有人可以帮忙吗?谢谢!

javascript knockout.js magento2
1个回答
0
投票

我建议将金额格式移至应用程序视图模型。这将使您更灵活地修改它。然后您可以轻松对其进行单元测试或进行调整以使用不同的文化和舍入。

class AppViewModel {
    constructor() {
        this.qty = 12;
        this.product_price_value = 23.7343999;
    }

    amountFmt() {
        const rounded = (this.qty * this.product_price_value).toFixed(2);
        return  Number(rounded).toLocaleString("de");
    }
}

ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
  Amount: <span data-bind="text: qty * product_price_value"></span><br />
  Amount formatted: <span data-bind="text: amountFmt()"></span><br />
    </div>

© www.soinside.com 2019 - 2024. All rights reserved.