Format rupiah javascript stackoverflow

Returns a NumberFormat for formatting and parsing currency values for the user's default locale. See "".

  • format

    Formats a number into a supplied buffer. The number must be a subclass of Number. Instances of Byte,

  • getInstance
  • setMaximumFractionDigits

    Sets the maximum number of fraction digits that are printed when formatting. If the maximum is less

  • getNumberInstance

    Returns a NumberFormat for formatting and parsing numbers for the specified locale.

  • parse
  • setGroupingUsed

    Sets whether this number format formats and parses numbers using a grouping separator.

  • setMinimumFractionDigits

    Sets the minimum number of fraction digits that are printed when formatting.

  • getPercentInstance

    Returns a NumberFormat for formatting and parsing percentage values for the given locale.The NumberF

  • setMinimumIntegerDigits

    Sets the minimum number of integer digits that are printed when formatting.

  • getIntegerInstance

    Returns a NumberFormat for formatting and parsing integers for the specified locale.

  • setParseIntegerOnly

    Specifies if this number format should parse numbers only as integers or else as any kind of number.

  • setMaximumIntegerDigits

    Sets the new maximum count of integer digits that are printed when formatting. If the maximum is les

  • setParseIntegerOnly,
  • setMaximumIntegerDigits,
  • getMaximumFractionDigits,
  • clone,
  • setCurrency,
  • getMinimumFractionDigits,
  • setRoundingMode,
  • getAvailableLocales,
  • parseObject

  • Running tasks concurrently on multiple threads
  • setScale (BigDecimal)
  • onCreateOptionsMenu (Activity)
  • setContentView (Activity)
  • PrintWriter (java.io)

    Wraps either an existing OutputStream or an existing Writerand provides convenience methods for prin

  • ConnectException (java.net)

    A ConnectException is thrown if a connection cannot be established to a remote host on a specific po

  • Scanner (java.util)

    A parser that parses a text string of primitive types and strings with the help of regular expressio

  • Stack (java.util)

    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u

  • TimeZone (java.util)

    TimeZone represents a time zone offset, and also figures out daylight savings. Typically, you get a

  • Callable (java.util.concurrent)

    A task that returns a result and may throw an exception. Implementors define a single method with no

  • From CI to AI: The AI layer in your organization

Many of the answers had helpful ideas, but none of them could fit my needs. So I used all the ideas and build this example:

function Format_Numb(fmt){
    var decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
    if(typeof decSgn === "undefined") decSgn = ".";
    if(typeof kommaSgn === "undefined") kommaSgn= ",";

    var s3digits = /(\d{1,3}(?=(\d{3})+(?=[.]|$))|(?:[.]\d*))/g;
    var dflt_nk = "00000000".substring(0, decimals);

    //--------------------------------
    // handler for pattern: "%m"
    var _f_money = function(v_in){
                       var v = v_in.toFixed(decimals);
                       var add_nk = ",00";
                       var arr = v.split(".");
                       return arr[0].toString().replace(s3digits, function ($0) {
                           return ($0.charAt(0) == ".")
                                   ? ((add_nk = ""), (kommaSgn + $0.substring(1)))
                                   : ($0 + decSgn);
                           })
                           + ((decimals > 0)
                                 ? (kommaSgn
                                       + (
                                           (arr.length > 1)
                                           ? arr[1]
                                           : dflt_nk
                                       )
                                   )
                                 : ""
                           );
                   }

    // handler for pattern: "%[.]f"
    var _f_flt = function(v_in, l, prec){
        var v = (typeof prec !== "undefined") ? v_in.toFixed(prec) : v_in;
        return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
                ? (Array(l+1).join(" ") + v)
                : v;
    }

    // handler for pattern: "%x"
    var _f_hex = function(v_in, l, flUpper){
        var v = Math.round(v_in).toString(16);
        if(flUpper) v = v.toUpperCase();
        return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
                ? (Array(l+1).join("0") + v)
                : v;
    }

    //...can be extended..., just add the function, for example:    var _f_octal = function( v_in,...){
    //--------------------------------

    if(typeof(fmt) !== "undefined"){
        //...can be extended..., just add the char, for example "O":    MFX -> MFXO
        var rpatt = /(?:%([^%"MFX]*)([MFX]))|(?:"([^"]*)")|("|%%)/gi;
        var _qu = "\"";
        var _mask_qu = "\\\"";
        var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){
                      var f;
                      if(typeof $1 !== "undefined"){
                          switch($2.toUpperCase()){
                              case "M": f = "_f_money(v)";    break;

                              case "F": var n_dig0, n_dig1;
                                        var re_flt =/^(?:(\d))*(?:[.](\d))*$/;
                                        $1.replace(re_flt, function($0, $1, $2){
                                            n_dig0 = $1;
                                            n_dig1 = $2;
                                        });
                                        f = "_f_flt(v, " + n_dig0 + "," + n_dig1 + ")";    break;

                              case "X": var n_dig = "undefined";
                                        var re_flt = /^(\d*)$/;
                                        $1.replace(re_flt, function($0){
                                            if($0 != "") n_dig = $0;
                                        });
                                        f = "_f_hex(v, " + n_dig + "," + ($2=="X") + ")";    break;
                              //...can be extended..., for example:    case "O":
                          }
                          return "\"+"+f+"+\"";
                      } else if(typeof $3 !== "undefined"){
                          return _mask_qu + $3 + _mask_qu;
                      } else {
                          return ($4 == _qu) ? _mask_qu : $4.charAt(0);
                      }
                  });

        var cmd =     "return function(v){"
                +     "if(typeof v === \"undefined\")return \"\";"  // null returned as empty string
                +     "if(!v.toFixed) return v.toString();"         // not numb returned as string
                +     "return \"" + str + "\";"
                + "}";

        //...can be extended..., just add the function name in the 2 places:
        return new Function("_f_money,_f_flt,_f_hex", cmd)(_f_money,_f_flt,_f_hex);
    }
}

First, I needed a C-style format-string-definition that should be flexible, but very easy to use and I defined it in following way; patterns:

%[][.]f   float, example "%f", "%8.2d", "%.3f"
%m                   money
%[]x            hexadecimal lower case, example "%x", "%8x"
%[]X            hexadecimal upper case, example "%X", "%8X"

Because there isn't any need to format others than to euro for me, I implemented only "%m".

But it's easy to extend this... Like in C, the format string is a string containing the patterns. For example, for euro: "%m €" (returns strings like "8.129,33 €")

Besides the flexibility, I needed a very fast solution for processing tables. That means that, when processing thousands of cells, the processing of format string must not be done more than once. A call like "format( value, fmt)" is not acceptable for me, but this must be split into two steps:

// var formatter = Format_Numb( "%m €");
// simple example for Euro...

//   but we use a complex example:

var formatter = Format_Numb("a%%%3mxx \"zz\"%8.2f°\"  >0x%8X<");

// formatter is now a function, which can be used more than once (this is an example, that can be tested:)

var v1 = formatter(1897654.8198344);

var v2 = formatter(4.2);

... (and thousands of rows)

Also for performance, _f_money encloses the regular expression;

Third, a call like "format( value, fmt)" is not acceptable because:

Although it should be possible to format different collections of objects (for example, cells of a column) with different masks, I don't want to have something to handle format strings at the point of processing. At this point I only want to use formatting, like in

for( var cell in cells){ do_something( cell.col.formatter( cell.value)); }

What format - maybe it's defined in an .ini file, in an XML for each column or somewhere else ..., but analyzing and setting formats or dealing with internationalizaton is processed in totally another place, and there I want to assign the formatter to the collection without thinking about performance issues:

col.formatter = Format_Numb( _getFormatForColumn(...) );

Fourth, I wanted an "tolerant" solution, so passing, for example, a string instead of a number should return simply the string, but "null" should return en empty string.

(Also formatting "%4.2f" must not cut something if the value is too big.)

And last, but not least - it should be readable and easy extendable, without having any effects in performance... For example, if somebody needs "octal values", please refer to lines with "...can be extended..." - I think that should be a very easy task.

My overall focus lay on performance. Each "processing routine" (for example, _f_money) can be encapsulated optimized or exchanged with other ideas in this or other threads without change of the "prepare routines" (analyze format strings and creation of the functions), which must only be processed once and in that sense are not so performance critical like the conversion calls of thousands of numbers.

For all, who prefer methods of numbers:

Number.prototype.format_euro = (function(formatter){
    return function(){ return formatter(this); }})
(Format_Numb( "%m €"));

var v_euro = (8192.3282).format_euro(); // results: 8.192,33 €

Number.prototype.format_hex = (function(formatter){
    return function(){ return formatter(this); }})
(Format_Numb( "%4x"));

var v_hex = (4.3282).format_hex();

Although I tested some, there may be a lot of bugs in the code. So it's not a ready module, but just an idea and a starting point for non-JavaScript experts like me.

The code contains many and little modified ideas from a lot of Stack Overflow posts; sorry I can't reference all of them, but thanks to all the experts.

How to set currency format in JavaScript?

NumberFormat() Constructor to Format Numbers as Currency. You can use the Intl. NumberFormat() constructor to create Intl. NumberFormat objects that enable language-sensitive number formatting, such as currency formatting.

How to format money in string JavaScript?

NumberFormat() Method. One of the best ways in JavaScript to format the number as a currency string is to use Intl. NumberFormat() method. You can pass the locale to the method as a parameter and set the dollar sign before the number and format number.

What is JavaScript stack overflow?

A stack overflow occurs when there is a recursive function (a function that calls itself) without an exit point. The browser (hosting environment) has a maximum stack call that it can accomodate before throwing a stack error.