# 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 : $strDefaultPrecision; 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 and 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 : strDefaultPrecision; // 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); }