简体   繁体   English

C#十进制tostring格式

[英]C# decimal tostring format

I want to create a string from a decimal, whithout the decimal separator; 我想从小数点创建一个字符串,而没有小数点分隔符;

1,500.00 should become "150000". 1,500.00应该变成“ 150000”。

What is the proper format for this? 什么是正确的格式? (Whithout string.replace , and .) (没有string.replace和。)

Thank you! 谢谢!

try: 尝试:

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

Two solutions: 两种解决方案:

  • Create your own NumberFormatInfo and CultureInfo and pass it along to ToString. 创建自己的NumberFormatInfo和CultureInfo并将其传递给ToString。
  • Multiply the number by 100, then use .ToString("0") 将数字乘以100,然后使用.ToString("0")

What's wrong with String.Replace anyway? String.Replace到底有什么问题? 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"
decimal value = 1500;
Console.WriteLine((value * 100).ToString("0"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM