theringostarrs
theringostarrs

Reputation: 12380

Formatting a large number with commas

I need to format a number so that there is a comma seperating the thousands place for any number over and including 10000. eg 10000 becomes 10,000 but 9999 remaains as 9999.

I would like to do this using a format string as I do not want to have to test the data to see if what range it is in.

Does anyone know how to do this?

Upvotes: 2

Views: 3805

Answers (4)

BlueMonkMN
BlueMonkMN

Reputation: 25601

There has to be a range check at some level. If you implement it like this, you can embed the range checking within the formatting framework to some extent, bypassing the default formatting (which includes group separators) if the number is fewer than 5 digits:

class MyFormat : System.IFormatProvider, ICustomFormatter
{
    #region IFormatProvider Members

    public object GetFormat(Type formatType)
    {
        return this;
    }

    #endregion


    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg is double)
            if (((double)arg >= 10000) || ((double)arg <= -10000))
                return ((double)arg).ToString(format);
            else
                return ((double)arg).ToString("R");

        if (arg is decimal)
            if (((decimal)arg >= 10000) || ((decimal)arg <= -10000))
                return ((decimal)arg).ToString(format);
            else
                return ((decimal)arg).ToString("R");

        return arg.ToString();
    }

    #endregion
}

class Program
{
    static MyFormat gFormat = new MyFormat();

    static void Main(string[] args)
    {

        double dblVal1 = 9999, dblVal2 = 123456;
        Console.WriteLine(String.Format(gFormat, "{0:N0} {1:N0}", dblVal1, dblVal2));
    }
}

Upvotes: 0

dtb
dtb

Reputation: 217293

A format string cannot behave differently for different values, so the best you can do is:

int n;

string s = n >= 10000 ? n.ToString("n0") : n.ToString("d");

(This will use the user's culture; pass a INumberFormatInfo/CultureInfo if a different culture is needed.)

MSDN: Standard and Custom Numeric Format Strings

Upvotes: 9

womp
womp

Reputation: 116977

I would suggest creating your own IFormatProvider that has a quick length check and formats it with the thousands separator normally if it's five or more characters, or without the thousands separator if it's four or less characters.

You could easily modify an example from the MSDN docs on IFormatProvider.

Upvotes: 2

Steve T
Steve T

Reputation: 7838

num > 9999 ? num.ToString("N0", CultureInfo.InvariantCulture) : num.ToString();

"N0" assuming you don't want decimals. NFormat

Upvotes: 2

Related Questions