Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

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.

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));

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

More Java Script Code:
• Basic State Machines
• Easy Moving Popup Code
• Use JavaScript parseInt() and parseFloat() to Convert Strings to Numbers
• JavaScript 24-Hour Trainer
• Calculators for Your Web Site : Loan Payment Calculator
• JavaScript Code for Binary to Decimal - Decimal to Binary Conversion
• Code for a Less annoying Popup Window
• Disable IE8 Accelerators on Your Website
• Creating Basic Java Script Functions
• Easy JavaScript Picture Selector Code

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro

Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2018 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268