views:

873

answers:

3

Is there a built in function of JavaScript to convert a string into a current format?

For example

var a = '1234';
a.convertToCurrency();   // return $1,234

UPDATE

Please note that I want the function to return the currency to include the US comma to group digits.

+1  A: 
var a = 1234.12;
var c = '$' + a.toLocaleString();
ChaosPandion
That doesn't add in the "," (commas)
TimH
Your example return $1234.12 but I want it to return $1,234
TimH
Unfortunately it depends on your system settings.
ChaosPandion
Do you know how to modify your example to have it include the comma (",") to group the digits?
TimH
A: 

This we did in one of our project long back. I just find out the code . Our application was in asp.net. Function dollarAmount does the work

function checkNum(data) {      // checks if all characters
     var valid = "0123456789.";     // are valid numbers or a "."
     var ok = 1; var checktemp;
     for (var i=0; i<data.length; i++) {
     checktemp = "" + data.substring(i, i+1);
     if (valid.indexOf(checktemp) == "-1") return 0; }
     return 1;
    }

    function dollarAmount(form, field, appendZero) 
    { 
     Num = "" + eval("document." + form + "." + field + ".value");

     if(Num=="")
     {
      eval("document." + form + "." + field + ".value = '" + 0 + "';");
      return;
     }

     dec = Num.indexOf(".");

     end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : "");

     Num = "" + parseInt(Num);

     var temp1 = "";
     var temp2 = "";
     //var appendZero=1;

     if (checkNum(Num) == 0) {
     //alert("This does not appear to be a valid number.  Please try again.");
     }
     else {

      if(appendZero==1 || end !="")
      {
       if (end.length == 2) end += "0";
       if (end.length == 1) end += "00";
       if (end == "") end += ".00";
      }

     var count = 0;
     for (var k = Num.length-1; k >= 0; k--) {
     var oneChar = Num.charAt(k);
     if (count == 3) {
     temp1 += ",";
     temp1 += oneChar;
     count = 1;
     continue;
     }
     else {
     temp1 += oneChar;
     count ++;
     }
     }
     for (var k = temp1.length-1; k >= 0; k--) {
     var oneChar = temp1.charAt(k);
     temp2 += oneChar;
     }
     temp2 = temp2 + end;
     eval("document." + form + "." + field + ".value = '" + temp2 + "';");
     }
    }

We called this function like this

txtBox.Attributes.Add("OnBlur", "return DollarAmount('" + txtBox.ID + "',0)");

Also after googling I found this links

a) Use JavaScript to Format Currency within Your Web Page

b) Currency Format

Also I guess that JQuery may have some plugin for serving the purpose Currency: an unobstrusive automatic and real time currency conversion

But I doubt if any inbuilt function is available in javascript. Please let me know if you found any. I would love to know.

Thanks .

priyanka.sarkar
There is no need to use eval....document.forms[form_name][field_name].value
ChaosPandion
+5  A: 

There is no built in function for currency format that works on every browser on every platform.

However, you can extend javascript with custom functions. This small (once you uncomment it) piece of code should cover it and any other currency you throw at it, it will even round your number if need arises:

Number.prototype.toCurrency = function($O) { // extending Number prototype

    String.prototype.separate_thousands = function() { // Thousands separation
     $val = this;
     var rx = new RegExp('(-?[0-9]+)([0-9]{3})');
     while(rx.test($val)) { $val = $val.replace(rx, '$1'+$O.thousands_separator+'$2'); }
     return $val;
    }

    Number.prototype.toFixed = function() { // Rounding
     var m = Math.pow(10,$O.use_fractions.fractions);
     return Math.round(this*m,0)/m;
    }

    String.prototype.times = function(by) { // String multiplication
     by = (by >> 0);
     var t = (by > 1? this.times(by / 2): '' );
     return t + (by % 2? t + this: t);
    }

    var $A = this;

    /* I like to keep all options, as the name would sugesst, **optional** :) so, let me make tham as such */
    $O ? null : $O = new Object;
    /* If no thousands_separator is present default to "," */
    $O.thousands_separator ? null : $O.thousands_separator = ",";
    /* If no currency_symbol is present default to "$" */
    $O.currency_symbol ? null : $O.currency_symbol = "$";

    // Fractions use is separated, just in case you don't want them
    if ($O.use_fractions) {
     $O.use_fractions.fractions ? null : $O.use_fractions.fractions = 2;
     $O.use_fractions.fraction_separator ? null : $O.use_fractions.fraction_separator = ".";  
    } else {
     $O.use_fractions = new Object;
     $O.use_fractions.fractions = 0;
     $O.use_fractions.fraction_separator = " ";
    }
    // We round this number
    $A.round = $A.toFixed();

    // We convert rounded Number to String and split it to integrer and fractions
    $A.arr = ($A.round+"").split(".");
    // First part is an integrer
    $A._int = $A.arr[0].separate_thousands();
    // Second part, if exists, are rounded decimals
    $A.arr[1] == undefined ? $A._dec = $O.use_fractions.fraction_separator+"0".times($O.use_fractions.fractions) : $A._dec = $O.use_fractions.fraction_separator+$A.arr[1];

    /* If no symbol_position is present, default to "front" */
    $O.symbol_position ? null : $O.symbol_position = "front";
    $O.symbol_position == "front" ? $A.ret = $O.currency_symbol+$A._int+$A._dec : $A.ret = $A._int+$A._dec+" "+$O.currency_symbol;
    return $A.ret;
}

And a nice way to call it goes as this:

/* Since we are extending Number prototype, amount **must** be a real number */
var amount = "12345.6789"; // But, in case it is not (like the above example: "string "), we need to convert it 
typeof(amount) == 'number' ? null : typeof(amount) == 'string' ? amount = parseFloat(amount) : null;
var currency_string =  amount.toCurrency({
         "thousands_separator":",",
         "currency_symbol":"$",
         "symbol_position":"front",
         "use_fractions" : { "fractions":2, "fraction_separator":"." }
         }); // 12345.6789 should return $12,345.68
Krule
Appears to have a bug: 0.5 formats as "0.5", not "0.50" (currency must be to 2 decimals not one)
JK