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

44u64gxh  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(50)

在Magento 2 minicart(CE 2.4.6)中,我不仅要显示购物车中每个项目的价格,而且还要显示每个项目的SUM(如果购物车中有多个相同项目的单位)。因此,我在minicart/item/default.html中添加了以下行:

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

字符串
输出为以下格式:89.699999999999
我需要欧洲格式与逗号分隔符和两个小数。所以我试着:

<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,69999999999
然而,我无法找到一种方法来实现逗号和小数位数。

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


这又一次只显示了正确的小数,但错误的分隔符。
有人能帮忙吗?谢谢!

jmo0nnb3

jmo0nnb31#

我建议将amount的格式移到应用程序viewmodel中。这将允许您更灵活地修改它。然后您可以轻松地对其进行单元测试或调整以使用不同的文化和舍入。如果您无法更新viewmodel,请调用外部函数 simpleNumberFormat

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");
    }
}

function simpleNumberFormat(amount) {
  return  Number(amount.toFixed(2)).toLocaleString("de", {minimumFractionDigits: 2});
}

ko.applyBindings(new AppViewModel());

个字符

相关问题