Incognito has asked for the wisdom of the Perl Monks concerning the following question:
# Pad the number with a bunch of zeros $strValue =~ s/^(\d*)\.?(\d*)$/${1}.${2}000000000/; # Remove all but the first '$strPrecision' digits that immediately # trail the decimal point. $strDefaultPrecision = 2; $strPrecision = ($strPrecision >= 0) ? $strPrecision : $strDefaultPrec +ision; if ($strPrecision == 0) { $strValue =~ s/^(\d*)\.?\d*$/$1/; } else { $strValue =~ s/^(\d*\.\d{$strPrecision})\d*$/$1/; }
function ConvertNumberToCurrency (strValue, strPrecision) { /* Takes a string that contains a number with optional decimal point an +d returns the number with 2 decimal places. An optional precision parameter is provided. Assumptions: - strValue cannot contain any non-numeric characters (0-9 and .), or + this will not work. - strPrecision must be numeric. - this function works to only 10 digits of accuracy. Usage: ConvertNumberToCurrency (""); ConvertNumberToCurrency (".5"); ConvertNumberToCurrency ("1"); ConvertNumberToCurrency ("3."); ConvertNumberToCurrency ("100", "4"); ConvertNumberToCurrency ("12.4", 1); ConvertNumberToCurrency ("12.56", 0); ConvertNumberToCurrency ("12.46435"); */ var strDefaultPrecision = 2; var regexTruncate; strValue += ""; // Convert any digits to string if (! strValue) { strValue = "0"; } // Convert empty string to 0 // Set any non-numeric values to 0 if (! strValue.match (/^\d+\.?$|\d+\.?\d*$|\d*\.?\d+$/)) { strValue += "0"; } // Add a leading 0 to any numbers starting with a decimal point if (strValue.match (/^\./)) { strValue = "0" + strValue; } // Set the default precision if no precision is provided. strPrecision = (strPrecision >= 0) ? strPrecision : strDefaultPrecis +ion; // Pad the number with a bunch of zeros strReplaceValue = "$1.$2" + "0000000000"; strValue = strValue.replace ( /^(\d*)\.?(\d*)$/, strReplaceValue); // Remove all but the first 'strPrecision' digits that immediately // trail the decimal point.. if (strPrecision == 0) { regexTruncate = new RegExp ("^(\\d*)\\.?\\d*$"); } else { regexTruncate = new RegExp ("^(\\d*\\.\\d{"+strPrecision+"})\\d*$" +); } strValue = strValue.replace (regexTruncate, "$1"); return (strValue); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by Albannach (Monsignor) on Nov 06, 2001 at 09:15 UTC | |
by Incognito (Pilgrim) on Nov 07, 2001 at 00:05 UTC | |
|
(jeffa) Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by jeffa (Bishop) on Nov 06, 2001 at 07:47 UTC | |
|
Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by Fastolfe (Vicar) on Nov 06, 2001 at 06:51 UTC | |
by Incognito (Pilgrim) on Nov 06, 2001 at 06:59 UTC | |
by Fastolfe (Vicar) on Nov 06, 2001 at 07:16 UTC | |
|
Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge
by rob_au (Abbot) on Nov 06, 2001 at 12:27 UTC |