Thursday, June 3, 2010

How to set the decimal points or decimals in Magento

I was screwing around with Magento to attempt on getting the decimal places to work.

Searching online, I found a solution: to edit a particular line of code in /public_html/lib/Zend/Currency.php.

All you have to do is to change line 62, "'precision' => 2" to "'precision' => 0" or to a number that you want. However this solution is purely hard-coded.



What if you have multiple websites that uses the same Magento system?

Here's the solution to it, I have created some code to assign the precision value:
*** WARNING: Perform a backup of Currency.php in the event something goes wrong! ***

- Firstly, open up /public_html/lib/Zend/Currency.php

-Add this line of code after around line 90, you should see several similar lines like:
$this->_options

Code to add
$this->_options['precision'] = self::getPrecision($currency, $this->_locale);

-Next, just add in the next block of code within the class itself. If you're not sure where to put it, you can just paste it just before the lines of code above
public function toCurrency

Here's the code:

public function getPrecision($currency = null, $locale = null)
{
if (($currency === null) and ($locale === null)) {
return $this->_options['symbol'];
}

$params = self::_checkParams($currency, $locale);

//get the precision
$format = Zend_Locale_Data::getContent($locale, 'currencynumber');

iconv_set_encoding('internal_encoding', 'UTF-8');
if (iconv_strpos($format, ';')) {
$format = iconv_substr($format, 0, iconv_strpos($format, ';'));
}

//knowing the number of digits after the decimal point
if (iconv_strpos($format, '.') == null) {
$precision = 0;
} else {
$precision = iconv_strlen($format)- 1 - iconv_strpos($format, '.');
}

return $precision;
}

- Next, save your Currency.php file and upload it back to /public_html/lib/Zend
- Lastly, edit the appropriate xml files to have the decimals set.

For example, here's the code for en_AU.xml which I am currently testing on.
Note that I have changed the angle brackets to square brackets for documentation purposes on a blog.

[?xml version="1.0" encoding="UTF-8" ?]
[!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.5/ldml.dtd"]
[ldml]
[identity]
[version number="$Revision: 1.46 $"/]
[generation date="$Date: 2007/08/21 16:11:36 $"/]
[language type="en"/]
[territory type="AU"/]
[/identity]
[numbers]
[currencyFormats]
[currencyFormatLength]
[currencyFormat]
[pattern]¤#,##0.00[/pattern]
[/currencyFormat]
[/currencyFormatLength]
[/currencyFormats]
[/numbers]
[/ldml]