Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

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

Format a Number as Currency

The easiest and most proper way to format a number as a currency value is to use the Java Script Number object's toFixed method, as shown below.

var n = 314.7614;
var amt = n.toFixed(2);

The argument passed to the toFixed method sets the number of digits to the right of the decimal point. The toFixed method rounds the number up and adds zeros after the decimal point if needed to create the desired decimal length.

The toFixed method will only work in newer browsers like Internet Explorer version 5.5 and later. If you can't be sure that all your users have newer browsers than you can create your own function to format a number as a currency, as shown below.

function toCurrency(num)
  var n = Math.round(num * 100) / 100;

  var m = n.toString();
  var loc = m.indexOf(".");
  if(loc < 0)
    loc = m.length;
    m += ".";

  while(loc + 3 > m.length)
    m += '0';
  return m;

The first line in the toCurrency function moves first two digits of the number from the right of decimal to left of the decimal point (or adds zeros if required), rounds the number, then puts the decimal point back where it was.

The number is then converted to a string and the index of the decimal point in the string is acquired. The if structure checks if there is no decimal point in the number. if not, it puts one at the end of the number.

The while structure makes sure there are two digits to right of the decimal point. If not. it adds zeros as required. The function then returns the currency formatted number.

The line below shows how you could pass a number to the toCurrency function.

var k = 120.6234;
var amt = toCurrency(k);

Or just pass the numeric value as shown below.

var amt = toCurrency(120.6234);

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-2024 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268