Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

How could I format this number as currency in Javascript?

Here's the currency function I want to use:

function number_format (number, decimals, dec_point, thousands_sep) {

    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/B(?=(?:d{3})+(?!d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

/**
*	Usage: 	number_format(123456.789, 2, '.', ',');
*	result:	123,456.79
**/

Open in new window


Downright elegant!

Now, here's my challenge:

I'm sending a value to a <span> tag via JavaScript that looks like this:

function addAllocated(form) {
//var theForm = document.form;
var numRows = form.allocatedlistcount.value;
//alert("allocated: " + numRows);

var total = 0;

    for( var rowIndex = 1; rowIndex <= numRows; rowIndex++ ) {
        eval('allocated = form.allocated_'+rowIndex+'.value');
       // total += document.getElementsByName("allocated_" + rowIndex).value;
       //alert('row: '+rowIndex+'; total: '+total);
       total = total + allocated*1;
       total_allocated.innerHTML = '<span class=\"info\">$'+total+'</span>';
       }
}

Open in new window


I want to format that "total" as currency. But how do you pull off a function within a function?

Thoughts?
0
brucegust
Asked:
brucegust
  • 2
1 Solution
 
Ken ButtersCommented:
I'm thinking you could update your total line like this:

total_allocated.innerHTML = '<span class=\"info\">$'+number_format(total, 2, '.', ',')+'</span>';

Open in new window

0
 
brucegustAuthor Commented:
Ken, when I do this:

total_allocated.innerHTML = '<span class=\"info\">$'+total+'</span>';

I get a number.

When I do this:

   total_allocated.innerHTML = '<span class=\"info\">$'+number_format(total, 2, '.', ',')+'</span>';

I don't get anything.

What am I missing?
0
 
brucegustAuthor Commented:
Never mind!

I got it!

Thanks so much!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now