3

I have a variable which is made up of a multiplication of 2 more variables

 var EstimatedTotal =  GetNumeric(ServiceLevel) * GetNumeric(EstimatedCoreHours);

Is it possible, and if so how, or what is the function called to format this as currency? I've been googling only I cant find a function and the only ways I've seen are really, really long winded

Liam
  • 9,537
  • 36
  • 106
  • 204
  • Possible duplicate of http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – goodeye Dec 05 '12 at 03:03

5 Answers5

9

Taken from here: http://javascript.internet.com/forms/currency-format.html. I've used it and it works well.

function formatCurrency(num)
{
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
    {
        num = "0";
    }

    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();

    if (cents < 10)
    {
        cents = "0" + cents;
    }
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }

    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}
James Hill
  • 58,309
  • 18
  • 142
  • 160
8

If you are looking for a quick function which would format your number (for example: 1234.5678) to something like: $1234.57 you may use .toFixed(..) method:

EstimatedTotal = "$" + EstimatedTotal.toFixed(2);

The toFixed function takes an integer value as the argument which means the number of trailing decimals. More information about this method can be found at http://www.w3schools.com/jsref/jsref_tofixed.asp.

Otherwise, if you would like to have your output format as: $1,234.57 you need to implement your own function for this. Below are two links with implementation:

dmitry7
  • 431
  • 3
  • 6
3

How abt using jQuery globalization plugin from microsoft? https://github.com/nje/jquery-glob

a6hi5h3k
  • 671
  • 3
  • 7
2

May not be perfect, but works for me.

if (String.prototype.ToCurrencyFormat == null) 
    String.prototype.ToCurrencyFormat = function() 
    { 
        if (isNaN(this * 1) == false)
            return "$" + (this * 1).toFixed(2); 
    }
Brett Weber
  • 1,821
  • 18
  • 22
0

There are no in-built functions for formatting currency in Javascript.

There are a number of scripts that you can find online that will help you with writing your own, however, here's one:

http://javascript.internet.com/forms/currency-format.html

Google "javascript currency".

James
  • 11,844
  • 1
  • 16
  • 19