Question

Is there a number format that would produce a localized number without the thousands separator?

 Globalize.format("1000.12", "n?" )

I realize I could do:

Globalize.culture().numberFormat[","]="";

But I have some fields where I want it off and some where it should be on. For example... If the value is:

1000.123 -> Want it to show formatted to 1000,12 or 1000.12 depending on locale..But without the thousands separator.

Was it helpful?

Solution

You can use the "d" format instead of the "n" format to exclude the thousands separator.

Globalize.format(1000.12, "d");

Edit
Note that this will only work if you don't care about the decimal part.

If you care about the decimal part, as far as I know, you can't exclude the thousands separator except through one of the following methods:

  1. Set the thousands character in the culture object to an empty string:

    Globalize.culture().numberFormat[","] = "";
    Globalize.format(1000.12, "n");
    

    You could turn this into a utility function fairly easily:

    function formatNumberNoThousands(num, format, culture) {
        var numberFormat = Globalize.cultures[culture || Globalize.culture().name].numberFormat,
            thousands = numberFormat[","];
        numberFormat[","] = "";
        try { return Globalize.format(num, format, culture); }
        finally { numberFormat[","] = thousands; }
    }
    
  2. Perform a replace on the string result of the format:

    Globalize.format(1000.12, "d").replace(new RegExp("\\" + Globalize.culture().numberFormat[","], "g"), "");
    

    Which can also be easily turned into a utility function:

    function formatNumberNoThousands(num, format, culture) {
        return Globalize.format(num, format).replace(new RegExp("\\" +  Globalize.culture(culture).numberFormat[","], "g"), "");
    }
    

    With this approach, if you know there will never be more than one thousands character in the formatted result you can remove the regexp. Otherwise if you plan on using this a lot or inside of a loop, you will want to cache the regexp and re-use it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top