【发布时间】:2011-12-28 20:33:37
【问题描述】:
我需要在这个标尺中将十进制转换为字符串:
120.00 - "120"
120.01 - "120.01"
120.50 - "120.50"
【问题讨论】:
-
十进制 d = 120.10m;字符串 ds = d.ToString("0.00").Replace(".00", string.Empty);还有其他情况吗?
我需要在这个标尺中将十进制转换为字符串:
120.00 - "120"
120.01 - "120.01"
120.50 - "120.50"
【问题讨论】:
使用decimal.ToString() 方法。如果需要,您可以使用该方法指定格式:
decimal d = 120.00;
string ds = d.ToString("#,#.00#");
// ds is a formated string of d's value
【讨论】:
您可以使用decimal.ToString 覆盖来指定格式。
decimal amount = 120.00m;
string str = amount.ToString("0.00");
这也可以在使用String.Format时使用。
Console.WriteLine("{0:0.00}", amount);
对于您的第一条规则,它不能在一行中完成。
decimal amount = 120.00m;
string str = amount.ToString("0.00").Replace(".00", String.Empty);
【讨论】:
decimal amount = 120.60m; string str = amount.ToString("0.00"); 时收到 cannot convert from double to string 发现我需要使用 amount.ToString("F6");。在我的情况下,我需要 6 个位置值,但我认为问题不是小数点的数量,因为如果我使用 string str = amount.ToString("0.00"); 或 string str = amount.ToString("0.000000"); 我使用的是 numeric 数据库字段,它会抱怨使用decimal 对象存储。遇到这个stackoverflow.com/questions/533931/convert-double-to-string - 这对我有帮助。
你可以使用decimal.Tostring()方法
请通过此链接查看more info
【讨论】:
5.00 打印为5,这在货币显示中是不可取的
根据您想要的格式,decimal.ToString 有不同的重载。
示例
decimal d = 5.00
Console.WriteLine(d.ToString("C")); // for currency
请参阅下面的其他重载... specifier 是您放入 ToString(specifier) 的内容
MSDN Documentation on Decimal.ToString
十进制值 = 16325.62m; 字符串说明符;
// Use standard numeric format specifiers.
specifier = "G";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: G: 16325.62
specifier = "C";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: C: $16,325.62
specifier = "E04";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: E04: 1.6326E+004
specifier = "F";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: F: 16325.62
specifier = "N";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: N: 16,325.62
specifier = "P";
Console.WriteLine("{0}: {1}", specifier, (value/10000).ToString(specifier));
// Displays: P: 163.26 %
// Use custom numeric format specifiers.
specifier = "0,0.000";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays: 0,0.000: 16,325.620
specifier = "#,#.00#;(#,#.00#)";
Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier));
// Displays: #,#.00#;(#,#.00#): (16,325.62)
【讨论】:
d.ToString("F6"); 将给出 5.000000 - 这有助于我将数据库中的 numeric 字段中的小数写入字符串。 d.ToString("0.00");给了我cannot convert from double to stringstackoverflow.com/questions/533931/convert-double-to-string