joop
joop

Reputation: 1

C# decimal tostring format

I want to create a string from a decimal, whithout the decimal separator;

1,500.00 should become "150000".

What is the proper format for this? (Whithout string.replace , and .)

Thank you!

Upvotes: 0

Views: 13006

Answers (4)

jason
jason

Reputation: 241591

What's wrong with String.Replace anyway? It's simple and to the point:

CultureInfo info = CultureInfo.GetCultureInfo("en-US");

decimal m = 1500.00m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000"

m = 1500.0m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "15000"

m = 1500.000m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500000"


m = 1500.001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "1500001"

m = 1500.00000000000000000000001m;
string s = m.ToString("G", info).Replace(".", String.Empty));
Console.WriteLine(s); // outputs "150000000000000000000000001"

Upvotes: 1

richardtallent
richardtallent

Reputation: 35363

Two solutions:

  • Create your own NumberFormatInfo and CultureInfo and pass it along to ToString.
  • Multiply the number by 100, then use .ToString("0")

Upvotes: 2

Charles Bretana
Charles Bretana

Reputation: 146429

try:

   decimal d = 1500m;
   string s = (100*d).ToString("0");

Upvotes: 7

Rubens Farias
Rubens Farias

Reputation: 57936

decimal value = 1500;
Console.WriteLine((value * 100).ToString("0"));

Upvotes: 0

Related Questions