Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a decimal without comma

Tags:

c#

.net

decimal

i try to format a decimal as 0:0.0 in c# tried this code

string nv = textBox7.Text.Trim().Replace(',', '.');

res =  Convert.ToDecimal(nv, new CultureInfo("en-GB"));

but res always show a result with a comma, tried also with

new CultureInfo("en-GB")

but the problem persist And thank you in advance.

like image 244
tarek Avatar asked Apr 21 '12 10:04

tarek


2 Answers

As other comments and answers suggest, you have some basics to understand first. I may be saying some things you already know, but bear with me:

  1. Your textBox7.Text contains a string, not a decimal.
  2. If you want a decimal for calculations, you have to convert it (I think you already got this far)
  3. Since res is a decimal, whenever you want to look at its value SOMETHING will convert it to a string. Whether that's you writing it to the Console or your debugger when you mouse over it. That conversion will use your current Regional Settings. This is why you always see a comma.
  4. To show it to somebody else or write it somewhere with the format YOU want, you'll have to specify a format or a CultureInfo.

a) Standard Format. Example:
Console.WriteLine(res.toString("F2"));
This will format 123456 with 2 numbers after the comma: 123456.00

b) Custom Format. Example:
Console.WriteLine(res.toString("[##-##-##]"));
This will output 123456 to something like [12-34-56]

c) CultureInfo. Example:
Console.WriteLine(res.ToString(CultureInfo.CreateSpecificCulture("nl-BE")));
This will output 1234.56 like in Belgium: with a comma 1234,56

Incidentally, I think en-GB also outputs to a comma :-)

d) Combine. Go nuts! Do both ! Example:
Console.WriteLine(res.ToString("F2", CultureInfo.CreateSpecificCulture("nl-BE")));
formats 123456 to 123456,00 !

like image 99
Vincent Vancalbergh Avatar answered Sep 29 '22 12:09

Vincent Vancalbergh


res is a decimal, not a string. So it can't have a format. Decimals are pure mathematical numbers without an associated format. The format only comes into existence when you convert a decimal to a string.

You can use res.ToString(CultureInfo.InvariantCulture) to produce a string that uses . as decimal separator.

like image 32
CodesInChaos Avatar answered Sep 29 '22 13:09

CodesInChaos