Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q723 How can I reformat a text field to display a money value, for example 100,000.00?

You are here: irt.org | FAQ | JavaScript | Number | Q723 [ previous next ]

Try this:

<SCRIPT LANGUAGE="JavaScript"><!--
function outputMoney(number) {
    return outputDollars(Math.floor(number-0) + '') + outputCents(number - 0);
}

function outputDollars(number) {
    if (number.length <= 3)
        return (number == '' ? '0' : number);
    else {
        var mod = number.length%3;
        var output = (mod == 0 ? '' : (number.substring(0,mod)));
        for (i=0 ; i < Math.floor(number.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= number.substring(mod+3*i,mod+3*i+3);
            else
                output+= ',' + number.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
}

function outputCents(amount) {
    amount = Math.round( ( (amount) - Math.floor(amount) ) *100);
    return (amount < 10 ? '.0' + amount : '.' + amount);
}

document.write(outputMoney(0)+'<BR>');
document.write(outputMoney(1)+'<BR>');
document.write(outputMoney(12.)+'<BR>');
document.write(outputMoney(123.0)+'<BR>');
document.write(outputMoney(123.01)+'<BR>');
document.write(outputMoney(1234.00)+'<BR>');
document.write(outputMoney(12345.1)+'<BR>');
document.write(outputMoney(123456.22)+'<BR>');
document.write(outputMoney(1234567.333)+'<BR>');
document.write(outputMoney(12345678.4444)+'<BR>');
document.write(outputMoney(123456789.55555)+'<BR>');
document.write(outputMoney(1234567890.666666)+'<BR>');
document.write(outputMoney('1234567890.666666')+'<BR>');
//--></SCRIPT>

Thanks to Jeff Freeman for providing a bug fix to outputCents().

The following was submitted by will rusk

function formatNumber (number) {
  number = '' + number;
  numberParts = new Array();
  numberParts = number.split(".");

  number = numberParts[0];

  if (number.length > 3) {
    var mod = number.length%3;
    var output = (mod > 0 ? (number.substring(0,mod)) : '');
    for (i=0 ; i < Math.floor(number.length/3) ; i++) {
      if ((mod ==0) && (i ==0)) {
        output+= number.substring(mod+3*i,mod+3*i+3);
      } else {
        output+= ',' + number.substring(mod+3*i,mod+3*i+3);
      }
    }
		
    if (numberParts.length == 2) {
      output = output + "." + numberParts[1];
    } 			
    return (output);
  } else {
    if (numberParts.length == 2) {
      number = number + "." + numberParts[1];
    }	
    return number;
  }
}	

Feedback on 'Q723 How can I reformat a text field to display a money value, for example 100,000.00?'

©2018 Martin Webb