Menu
Display a Value in Currency Format

To display a currency value with the proper number of digits to the right of the decimal point, first use the Math.pow function to calculate a multiplier, then use that multiplier to round the number to the required number of digits.

Convert that value to a string so you can determine the location of the decimal point, or if you need to add a decimal point, and if you need to add zeros to the decimal portion. Code to convert a value to currency format is shown below.

<script>
function formatTo(value, precision)
{
   // calculate multiplier required to get required number
   // of digits to the right of the decimal point
   var multiplier = Math.pow(10, precision);

   // round value to required number of digits
   var amount = Math.round(value * multiplier) / multiplier;

   // convert to string
   var strAmt = amount.toString();

   // determine if you need to add zeros to decimal part
   var decimalIndex = strAmt.indexOf(".");
   if(precision > 0 && decimalIndex < 0)
   {
      decimalIndex = strAmt.length;
      strAmt += '.';
   }

   // add any required zeros to decimal part
   while(decimalIndex + precision + 1 > strAmt.length)
   {
      strAmt += '0';
   }
   return strAmt;
}

document.write(formatTo(4.003, 2));
</script>

Call the formatTo function, passing the value to format and the precision (number of digits to the right of the decimal point.


Learn more at amazon.com

More Java Script Code:
• A JavaScript Function That Returns a Function
• Regular Expressions Subexpressions
• Let Your Web site Visitors Set Font Size
• Java Script Code to Move Items Between Select Lists
• Password Protection Using the Frames Method
• Java Script Code for Directory File List
• Easy Code to Sort a Table by Column
• JavaScript to Add and Remove Rows and Cells from a Table
• Regular Expression Basics : Match a Set of Characters
• Round a Float to 4 Digits to the Right of the Decimal Point