Format decimal thousands

L

Luigi

Hi all,
with this code:

decimal? test = 1200345.56m;
decimal? test2 = Decimal.Parse(String.Format("{0:0,0.000}", test));

i can not obtain a decimal value with thousands separators (but without
Decimal.Parse do).

How can i solve?

Thanks in advance
 
M

Marc Gravell

Can you clarify what you are trying to do? A decimal is just a number -
it never really contains any separators. The string version might, but
you've already demonstrated that with your String.Format and Parse usage.

Marc
 
G

GArlington

Hi all,
with this code:

decimal? test = 1200345.56m;
decimal? test2 = Decimal.Parse(String.Format("{0:0,0.000}", test));
As you have multiple possible decimal separators [BOTH comma AND DOT
are used in different locales] in your string, you will have to use
the Parse function specifying which particular format applies...
 
M

Marc Gravell

I don't see why... both the Format and Parse will take the culture into
account. In the format string the . and , are palceholders for the
decimal and thousand separators (they aren't used verbatim). So this
code should work "as is":

static decimal? TestRoundtrip()
{
decimal? test = 1200345.56m;
string s = String.Format("{0:0,0.000}", test);
decimal? test2 = Decimal.Parse(s);
Console.WriteLine(test2);
return test2;
}
static void Main()
{
decimal? a, b;
Thread.CurrentThread.CurrentCulture =
CultureInfo.GetCultureInfo("fr-FR");
a=TestRoundtrip();
Thread.CurrentThread.CurrentCulture =
CultureInfo.GetCultureInfo("en-GB");
b=TestRoundtrip();
Console.WriteLine(a==b); // returns true
}
 
L

Luigi

Hi Marc,
how can I write a method that returns me a decimal type from a string value
that has both comma or dot?

For example:

string s1 = "12.34" -> decimal 12.34m
string s2 = "12,34" -> decimal 12.34m

Thanks a lot.

Luigi
 
A

Arne Vajhøj

Luigi said:
how can I write a method that returns me a decimal type from a string value
that has both comma or dot?

For example:

string s1 = "12.34" -> decimal 12.34m
string s2 = "12,34" -> decimal 12.34m

Do a simple replace and Parse based on what you
replaced it to.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top