3

How to display product price on listing page, product detail page in numbers & letters combination.

For example 2.5 lac, 3 crore etc. In PHP I can get price using following logic, but how to implement it in Magento2?

<?php

namespace Dcw\Search\Helper;
use Magento\Framework\App\Helper\Context;
class Price extends \Magento\Framework\App\Helper\AbstractHelper {




    public function __construct(
    Context $context
    , array $data = []
    ) {
        parent::__construct($context);
    }

    /**
     * 
     * @return type
     */
    public function getPrice($num) {

    $ext="";//thousand,lac, crore
    $number_of_digits = $this->count_digit($num); //this is call :)
      if($number_of_digits>3)
        {
            if($number_of_digits%2!=0)
              $divider=$this->divider($number_of_digits-1);
            else
               $divider=$this->divider($number_of_digits);
        }
        else
         $divider=1;

        $fraction=$num/$divider;
        $fraction=number_format($fraction,2);
        if($number_of_digits==4 ||$number_of_digits==5)
         $ext="k";
        if($number_of_digits==6 ||$number_of_digits==7)
          $ext="Lac";
        if($number_of_digits==8 ||$number_of_digits==9)
            $ext="Cr";

        return $fraction." ".$ext;
    }


protected function count_digit($number) {
  return strlen($number);
}

protected function divider($number_of_digits) {
    $tens="1";

  if($number_of_digits>8)
    return 10000000;

  while(($number_of_digits-1)>0)
  {
    $tens.="0";
    $number_of_digits--;
  }
  return $tens;
}



}
4
+100

app/code/Package/Modulename/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;
    }
}

Source:

Obviously the currency/locale would need to be changed but your question is how to approach implementing the currency format.

Also, a perhaps a more elegant GST currency converter method:

function formatCurrency(number) {
    var numberStr = number.toString();
    var thousandsMatcher = /(\d+)(\d{3})$/;
    var thousandsAndRest = thousandsMatcher.exec(numberStr);
    if (!thousandsAndRest) return numberStr;
    return thousandsAndRest[1].replace(/\B(?=(\d{2})+(?!\d))/g, ",") + "," + thousandsAndRest[2];
}

Lastly, there's this open source currency-format module that may offer some insight or a direct solution to the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.