M. Carlo Bramini
M. Carlo Bramini

Reputation: 2522

Decimal not showing group(thousand) separator after parse

In console application I've created 2 decimals:

  1. using literal value
  2. using a string parse

I've set my culture to "en-GB"

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-GB");

Decimal money = 14343431.948M;
Decimal moneyConversion = decimal.Parse("-34,555.897"); 

string decimalString = money.ToString("N3");
string moneyConversionString = moneyConversion.ToString("N3");

Console.WriteLine("Decimal value: " + decimalString); //prints 14,343,431.948
Console.WriteLine("Decimal value Converted: " + moneyConversion); //-34555.897

The first writeline shows the decimal representation as expected while the second prints -34555.897 but I was expecting -34,555.897, I'm missing the comma that separates the thousands. How come?

Upvotes: 1

Views: 141

Answers (2)

adrianbanks
adrianbanks

Reputation: 82944

You are printing out the value of the decimal (i.e. moneyConversion), not the string representation of it (moneyConversionString).

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500165

This is the problem:

Console.WriteLine("Decimal value Converted: " + moneyConversion); //-34555.897

You're using moneyConversion (the decimal value) rather than moneyConversionString. If you change it to:

Console.WriteLine("Decimal value Converted: " + moneyConversionString);

you'll get the formatting you expect. Otherwise you're just effectively calling moneyConversion.ToString() which will use the default "G" format.


Upvotes: 2

Related Questions