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.
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:
textBox7.Text
contains a string
, not a decimal
.decimal
for calculations, you have to convert it (I think you already got this far)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.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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With