notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

Formatting a decimal value with ToString() to have commas as thousand separators where the amount of decimal places is unknown

I have many decimals, each rounded differently:

decimal quantity = Decimal.Round(item.Quantity.Value, 2, 
    MidpointRounding.AwayFromZero);
decimal difference = Decimal.Round(quantity * eva, 0, 
    MidpointRounding.AwayFromZero);

When binding to the UI, I convert to string like this:

string Quantity = quantity.ToString("G", CultureInfo.InvariantCulture);
string Difference = difference.ToString("G", CultureInfo.InvariantCulture);

Is there a generic way to insert commas for thousand separators while keeping the original decimal rounding the same?

Upvotes: 1

Views: 4125

Answers (3)

notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

For anyone wondering, I ended up using String.Format(new CultureInfo("en-US"), "{0:N}", difference) and changed the N depending on how many decimal places I needed.

Upvotes: 2

JNL
JNL

Reputation: 4713

Try using Format.

        double d = 1.234567;
        String output = d.ToString("#,##0.##");

Also,

double d = 123456789.1;
string format = d.ToString().
                  IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) 
                  >=0 ? "#,##0.00" : "#,##0";
Console.WriteLine (d.ToString(format));

Upvotes: 4

jac
jac

Reputation: 9726

You can use the "N" format specifier and supply the number of digits you want any number to retain. If you want each number to potentially have a different number of digits you wall have to determine the number to supply to the format string each time.

quantity.ToString("N(digits)");

Complete documentation is at http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#NFormatString

Upvotes: 0

Related Questions