From db9e0947e008ba06308da5664e5c36a3bc2736df Mon Sep 17 00:00:00 2001 From: Sandor Semsey Date: Mon, 17 Feb 2020 23:11:37 +0100 Subject: [PATCH] CRM-21541 CRM.moneyFormat can't handle values with zero or one decimals (#16445) * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * CRM.formatMoney() handles zero or one decimals * missing semicolon * comment * comment * comment * comment --- js/Common.js | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/js/Common.js b/js/Common.js index fca7ef9abc..f4c2a60a6f 100644 --- a/js/Common.js +++ b/js/Common.js @@ -1491,27 +1491,42 @@ if (!CRM.vars) CRM.vars = {}; */ var currencyTemplate; CRM.formatMoney = function(value, onlyNumber, format) { - var decimal, separator, sign, i, j, result; + var precision, 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) { + if ((result = /1(.?)234(.?)56/.exec(format)) !== null) { // If value is formatted to 2 decimals + precision = 2; + } + else if ((result = /1(.?)234(.?)6/.exec(format)) !== null) { // If value is formatted to 1 decimal + precision = 1; + } + else if ((result = /1(.?)235/.exec(format)) !== null) { // If value is formatted to zero decimals + precision = false; + } + else { return 'Invalid format passed to CRM.formatMoney'; } separator = result[1]; - decimal = result[2]; + decimal = precision ? result[2] : false; 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) : ''); - if ( onlyNumber ) { + result = sign + (j ? i.substr(0, j) + separator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separator) + (precision ? decimal + Math.abs(value - i).toFixed(precision).slice(2) : ''); + if (onlyNumber) { return result; } - return format.replace(/1.*234.*56/, result); + switch (precision) { + case 2: + return format.replace(/1.*234.*56/, result); + case 1: + return format.replace(/1.*234.*6/, result); + case false: + return format.replace(/1.*235/, result); + } }; CRM.angRequires = function(name) { -- 2.25.1