如何在Magento 2中更改货币格式?


8

目前价格显示为$ 2.999,00

我希望产品页面上的语言环境es_MX(西班牙语,墨西哥)的价格显示为$ 2,999.00 ,其他任何货币格式正确的地方。

我已经尝试了stackexchange中的所有解决方案,但没有人能解决。

文件app / code / Jsp / Currency / etc / di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Framework\Locale\Format" type="Jsp\Currency\Model\Format"/>
</config>

档案app / code / Jsp / Currency / Model / Format.php

<?php
namespace Jsp\Currency\Model;

use Magento\Framework\Locale\Bundle\DataBundle;

class Format extends \Magento\Framework\Locale\Format
{
    private static $defaultNumberSet = 'latn';

    public function getPriceFormat($localeCode = null, $currencyCode = null)
    {
        $localeCode = $localeCode ?: $this->_localeResolver->getLocale();
        if ($currencyCode) {
            $currency = $this->currencyFactory->create()->load($currencyCode);
        } else {
            $currency = $this->_scopeResolver->getScope()->getCurrentCurrency();
        }

        $localeData = (new DataBundle())->get($localeCode);
        $defaultSet = $localeData['NumberElements']['default'] ?: self::$defaultNumberSet;

        $format = $localeData['NumberElements'][$defaultSet]['patterns']['currencyFormat']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['patterns']['currencyFormat']
                ?: explode(';', $localeData['NumberPatterns'][1])[0]);

        //your main changes are gone here.....
        if($localeCode == 'es_MX'){
            $decimalSymbol = '.';
            $groupSymbol = ',';
        }else{
            $decimalSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['decimal']
                ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['decimal']
                    ?: $localeData['NumberElements'][0]);

            $groupSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['group']
                ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['group']
                    ?: $localeData['NumberElements'][1]);
        }

        $pos = strpos($format, ';');
        if ($pos !== false) {
            $format = substr($format, 0, $pos);
        }
        $format = preg_replace("/[^0\#\.,]/", "", $format);
        $totalPrecision = 0;
        $decimalPoint = strpos($format, '.');
        if ($decimalPoint !== false) {
            $totalPrecision = strlen($format) - (strrpos($format, '.') + 1);
        } else {
            $decimalPoint = strlen($format);
        }
        $requiredPrecision = $totalPrecision;
        $t = substr($format, $decimalPoint);
        $pos = strpos($t, '#');
        if ($pos !== false) {
            $requiredPrecision = strlen($t) - $pos - $totalPrecision;
        }

        if (strrpos($format, ',') !== false) {
            $group = $decimalPoint - strrpos($format, ',') - 1;
        } else {
            $group = strrpos($format, '.');
        }
        $integerRequired = strpos($format, '.') - strpos($format, '0');

        $result = [
            //TODO: change interface
            'pattern' => $currency->getOutputFormat(),
            'precision' => $totalPrecision,
            'requiredPrecision' => $requiredPrecision,
            'decimalSymbol' => $decimalSymbol,
            'groupSymbol' => $groupSymbol,
            'groupLength' => $group,
            'integerRequired' => $integerRequired,
        ];       
        return $result;
    }
}

文件供应商/magento/framework/Locale/Format.php

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\Locale;

use Magento\Framework\Locale\Bundle\DataBundle;

class Format implements \Magento\Framework\Locale\FormatInterface
{
    /**
     * @var string
     */
    private static $defaultNumberSet = 'latn';

    /**
     * @var \Magento\Framework\App\ScopeResolverInterface
     */
    protected $_scopeResolver;

    /**
     * @var \Magento\Framework\Locale\ResolverInterface
     */
    protected $_localeResolver;

    /**
     * @var \Magento\Directory\Model\CurrencyFactory
     */
    protected $currencyFactory;

    /**
     * @param \Magento\Framework\App\ScopeResolverInterface $scopeResolver
     * @param ResolverInterface $localeResolver
     * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
     */
    public function __construct(
        \Magento\Framework\App\ScopeResolverInterface $scopeResolver,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        \Magento\Directory\Model\CurrencyFactory $currencyFactory
    ) {
        $this->_scopeResolver = $scopeResolver;
        $this->_localeResolver = $localeResolver;
        $this->currencyFactory = $currencyFactory;
    }

    /**
     * Returns the first found number from an string
     * Parsing depends on given locale (grouping and decimal)
     *
     * Examples for input:
     * '  2345.4356,1234' = 23455456.1234
     * '+23,3452.123' = 233452.123
     * ' 12343 ' = 12343
     * '-9456km' = -9456
     * '0' = 0
     * '2 054,10' = 2054.1
     * '2'054.52' = 2054.52
     * '2,46 GB' = 2.46
     *
     * @param string|float|int $value
     * @return float|null
     */
    public function getNumber($value)
    {
        if ($value === null) {
            return null;
        }

        if (!is_string($value)) {
            return floatval($value);
        }

        //trim spaces and apostrophes
        $value = str_replace(['\'', ' '], '', $value);

        $separatorComa = strpos($value, ',');
        $separatorDot = strpos($value, '.');

        if ($separatorComa !== false && $separatorDot !== false) {
            if ($separatorComa > $separatorDot) {
                $value = str_replace('.', '', $value);
                $value = str_replace(',', '.', $value);
            } else {
                $value = str_replace(',', '', $value);
            }
        } elseif ($separatorComa !== false) {
            $value = str_replace(',', '.', $value);
        }

        return floatval($value);
    }

    /**
     * Functions returns array with price formatting info
     *
     * @param string $localeCode Locale code.
     * @param string $currencyCode Currency code.
     * @return array
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function getPriceFormat($localeCode = null, $currencyCode = null)
    {
        $localeCode = $localeCode ?: $this->_localeResolver->getLocale();
        if ($currencyCode) {
            $currency = $this->currencyFactory->create()->load($currencyCode);
        } else {
            $currency = $this->_scopeResolver->getScope()->getCurrentCurrency();
        }
        $localeData = (new DataBundle())->get($localeCode);
        $defaultSet = $localeData['NumberElements']['default'] ?: self::$defaultNumberSet;
        $format = $localeData['NumberElements'][$defaultSet]['patterns']['currencyFormat']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['patterns']['currencyFormat']
                ?: explode(';', $localeData['NumberPatterns'][1])[0]);

        $decimalSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['decimal']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['decimal']
                ?: $localeData['NumberElements'][0]);

        $groupSymbol = $localeData['NumberElements'][$defaultSet]['symbols']['group']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['symbols']['group']
                ?: $localeData['NumberElements'][1]);

        $pos = strpos($format, ';');
        if ($pos !== false) {
            $format = substr($format, 0, $pos);
        }
        $format = preg_replace("/[^0\#\.,]/", "", $format);
        $totalPrecision = 0;
        $decimalPoint = strpos($format, '.');
        if ($decimalPoint !== false) {
            $totalPrecision = strlen($format) - (strrpos($format, '.') + 1);
        } else {
            $decimalPoint = strlen($format);
        }
        $requiredPrecision = $totalPrecision;
        $t = substr($format, $decimalPoint);
        $pos = strpos($t, '#');
        if ($pos !== false) {
            $requiredPrecision = strlen($t) - $pos - $totalPrecision;
        }

        if (strrpos($format, ',') !== false) {
            $group = $decimalPoint - strrpos($format, ',') - 1;
        } else {
            $group = strrpos($format, '.');
        }
        $integerRequired = strpos($format, '.') - strpos($format, '0');

        $result = [
            //TODO: change interface
            'pattern' => $currency->getOutputFormat(),
            'precision' => $totalPrecision,
            'requiredPrecision' => $requiredPrecision,
            'decimalSymbol' => $decimalSymbol,
            'groupSymbol' => $groupSymbol,
            'groupLength' => $group,
            'integerRequired' => $integerRequired,
        ];

        return $result;
    }
}

请检查更新的答案,如果您有任何问题让我知道,这是您问题的有效代码。我在西班牙语网站上遇到了同样的问题,并使用下面的代码解决了。谢谢。
Rakesh Jesadiya

删除代码中的条件,仅保留$ decimalSymbol ='。然后$ groupSymbol =','删除var并检查。有关更多信息,请保持更新的代码。请检查一下。
Rakesh Jesadiya

请检查您的自定义模块函数是否被调用,如果您的代码是否传入getPriceFormat函数中,则可以调试上述函数。原因代码对我来说正好适合我面临的相同类型的问题。
Rakesh Jesadiya

我注意到您提供的Format.php文件与您提供的文件略有不同。这可能是问题吗?关于调试功能,您能否更详细地说明如何调试它?
路易斯·加西亚

我是否需要在我的模块文件夹中添加一个registration.php文件?
路易斯·加西亚

Answers:


16

创建仅简单的模块和替代程序默认的* Format.php **文件,

应用程序/代码/包/模块名称/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Framework\Locale\Format" type="Vendor\Currency\Model\Format" />
</config>

创建模型文件, app / code / Package / Modulename / Model / Format.php

<?php
namespace Package\Modulename\Model;

use Magento\Framework\Locale\Bundle\DataBundle;

class Format extends \Magento\Framework\Locale\Format
{
    private static $defaultNumberSet = 'latn';

    public function getPriceFormat($localeCode = null, $currencyCode = null)
    {
        $localeCode = $localeCode ?: $this->_localeResolver->getLocale();
        if ($currencyCode) {
            $currency = $this->currencyFactory->create()->load($currencyCode);
        } else {
            $currency = $this->_scopeResolver->getScope()->getCurrentCurrency();
        }

        $localeData = (new DataBundle())->get($localeCode);
        $defaultSet = $localeData['NumberElements']['default'] ?: self::$defaultNumberSet;

        $format = $localeData['NumberElements'][$defaultSet]['patterns']['currencyFormat']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['patterns']['currencyFormat']
                ?: explode(';', $localeData['NumberPatterns'][1])[0]);

        //your main changes are gone here.....
        $decimalSymbol = '.';
        $groupSymbol = ',';

        $pos = strpos($format, ';');
        if ($pos !== false) {
            $format = substr($format, 0, $pos);
        }
        $format = preg_replace("/[^0\#\.,]/", "", $format);
        $totalPrecision = 0;
        $decimalPoint = strpos($format, '.');
        if ($decimalPoint !== false) {
            $totalPrecision = strlen($format) - (strrpos($format, '.') + 1);
        } else {
            $decimalPoint = strlen($format);
        }
        $requiredPrecision = $totalPrecision;
        $t = substr($format, $decimalPoint);
        $pos = strpos($t, '#');
        if ($pos !== false) {
            $requiredPrecision = strlen($t) - $pos - $totalPrecision;
        }

        if (strrpos($format, ',') !== false) {
            $group = $decimalPoint - strrpos($format, ',') - 1;
        } else {
            $group = strrpos($format, '.');
        }
        $integerRequired = strpos($format, '.') - strpos($format, '0');

        $result = [
            //TODO: change interface
            'pattern' => $currency->getOutputFormat(),
            'precision' => $totalPrecision,
            'requiredPrecision' => $requiredPrecision,
            'decimalSymbol' => $decimalSymbol,
            'groupSymbol' => $groupSymbol,
            'groupLength' => $group,
            'integerRequired' => $integerRequired,
        ];       
        return $result;
    }
}

谢谢。


我尝试了您的解决方案,但是没有用。我用创建的di.xml代码更新了答案。我还创建了模型文件,将“包和模块”名称更改为与我的文件夹名称相匹配
Luis Garcia

我已经用Format.php代码更新了我的问题。谢谢
路易斯·加西亚

我在上面尝试过,它适用于产品页面,但不适用于类别页面,想知道!!!
Zinat

它适用于整个网站。请检查是否有问题;
Rakesh Jesadiya

@RakeshJesadiya,其仅用于产品详细信息页面和其他价格(如总计,购物车等),但不适用于列表页面,迷你购物车,购物车项目价格
Codrain Technolabs Pvt Ltd

3

使用以下代码:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->create('\Magento\Framework\Pricing\PriceCurrencyInterface')->format('999,00',true,0);

格式化功能如下:

public function format(
        $amount,
        $includeContainer = true,
        $precision = self::DEFAULT_PRECISION,
        $scope = null,
        $currency = null
    );

如果$ includeContainer = true,则价格将与跨度容器一起显示

<span class="price">$999</span>

$precision = self::DEFAULT_PRECISION它将显示两个小数点。使用0将不会显示小数点。


我应该在哪个文件中添加此代码?我是Magento的新手,
路易斯·加西亚

我应该在哪个文件中添加此代码?
路易斯·加西亚

3

Magento 2默认情况下,某些货币的价格格式有些奇怪,因此我们需要对其进行更改。这是更改价格格式的方法。

这是越南盾的例子。默认显示格式为100.000,00。然后,我将其更改为100,000(用逗号分隔,不带小数点)。

# vendor/magento/zendframework1/library/Zend/Locale/Data/vi.xml
<symbols numbersystem="latn">
 <decimal>.</decimal>
 <group>,</group>
</symbols>

# vendor/magento/framework/Pricing/PriceCurrencyInterface.php
const DEFAULT_PRECISION = 0

# vendor/magento/module-directory/Model/Currency.php
return $this->formatPrecision($price, 0, $options, $includeContainer, $addBrackets);

# vendor/magento/module-sales/Model/Order.php
public function formatPrice($price, $addBrackets = false)
{
    return $this->formatPricePrecision($price, 0, $addBrackets);
}

谢谢享受:)


尝试过但是对es_MX不起作用
Luis Garcia

1
  1. 从您的根文件夹转到vendor / magento / zendframework1 / library / Zend / Locale / Data / es_MX.xml
  2. 寻找 <currencyFormat

您可以这样设置格式:

<currencyFormat type="standard">
    <pattern draft="contributed">¤#,##0.00</pattern>
</currencyFormat>

这种格式已经设置好了
路易斯·加西亚

0

要更改或删除不同货币的小数,只需从Mageplaza安装免费模块Currency Formatter Extension,即可在以下链接:https ://www.mageplaza.com/magento-2-currency-formatter/    。

然后,您可以从magento管理面板->商店->配置-> Mageplaza Extensions中为您的要求配置小数。 

这在magento 2.3.3安装中对我有用。 

最好的祝福


-1

不好的方法(但更快)是硬编码vendor / magento / framework / Locale / Format.php

    $result = [
        //TODO: change interface
        'pattern' => $currency->getOutputFormat(),
        'precision' => $totalPrecision,
        'requiredPrecision' => $requiredPrecision,
        //'decimalSymbol' => $decimalSymbol,
        'decimalSymbol' =>'.',
        //'groupSymbol' => $groupSymbol,
        'groupSymbol' => ',',
        'groupLength' => $group,
        'integerRequired' => $integerRequired,
    ];

如果这是一个不好的方法,那为什么要建议呢?我们永远不要修改核心或供应商。
Danny Nimmo'7

谢谢。我正在寻找一种快速解决问题的解决方案,因为我想修复一个濒死的网站,而我正在研究它的新版本。
哈桑·杰西
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.