From 5ec182d97970876d18a35032d3b7d79757799bdb Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Wed, 14 Aug 2013 13:28:48 -0700 Subject: [PATCH] Add client-side money formatting --- CRM/Core/Resources.php | 5 +++-- js/Common.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CRM/Core/Resources.php b/CRM/Core/Resources.php index 4868cba491..4854e9aac4 100644 --- a/CRM/Core/Resources.php +++ b/CRM/Core/Resources.php @@ -453,9 +453,10 @@ class CRM_Core_Resources { } } - // Initialize CRM.url + // Initialize CRM.url and CRM.formatMoney $url = CRM_Utils_System::url('civicrm/example', 'placeholder', FALSE, NULL, FALSE); - $js = "CRM.url('init', '$url');"; + $js = "CRM.url('init', '$url');\n"; + $js .= "CRM.formatMoney('init', '" . CRM_Utils_Money::format(1234.56) . "');"; $this->addScript($js, $jsWeight++, $region); // Add global settings diff --git a/js/Common.js b/js/Common.js index 457e3d77c6..09e65a0319 100644 --- a/js/Common.js +++ b/js/Common.js @@ -879,4 +879,33 @@ CRM.validate = CRM.validate || { $(this).toggleClass('collapsed'); }); }; + + /** + * Clientside currency formatting + * @param value + * @param format + * @return string + */ + var currencyTemplate; + CRM.formatMoney = function(value, format) { + var decimal, separator, sign, i, j, result; + if (value === 'init' && format) { + currencyTemplate = format; + return; + } + format = format || currencyTemplate; + result = /1(.?)234(.?)56/.exec(format); + if (result === null) { + return 'Invalid format passed to CRM.formatMoney'; + } + separator = result[1]; + decimal = result[2]; + sign = (value < 0) ? '-' : ''; + //extracting the absolute value of the integer part of the number and converting to string + i = parseInt(value = Math.abs(value).toFixed(2)) + ''; + + j = ((j = i.length) > 3) ? j % 3 : 0; + result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (2 ? decimal + Math.abs(value - i).toFixed(2).slice(2) : ''); + return format.replace(/1.*234.*56/, result); + }; })(jQuery); -- 2.25.1