我的字符串是1799.00
我想要这样的:1.799,00
但是我无法转换这个方法。
我正在使用这个功能。
public static decimal ToDecimal(this object str)
{
if (str != null)
{
try
{
return Convert.ToDecimal(str, new CultureInfo("tr-TR"));
}
catch (Exception)
{
return 0;
}
}
else
{
return 0;
}
}
最佳答案
您可能正在寻找变化的格式。给定一个小数作为固定区域性表示形式 ("1799.00"
) 中的字符串,您需要一个字符串,但采用土耳其文化表示形式: ("1.799,00"
)
// you want to return string in Turkish culture, right?
public static string ToTuskishDecimal(this object value) {
if (null == value)
return null; // or throw exception, or return "0,00" or return "?"
try {
return Convert
.ToDecimal(value, CultureInfo.InvariantCulture)
.ToString("N", CultureInfo.GetCultureInfo("tr-TR"));
}
catch (FormatException) {
return "0,00"; // or "?"
}
}
测试:
decimal d = 1799.00m;
string s = d.ToString(CultureInfo.InvariantCulture);
// 1.799,00
Console.Write(d.ToTuskishDecimal());
// 1.799,00
Console.Write(s.ToTuskishDecimal());
如果您想返回十进制
,则在打印时必须手动格式化:
public static decimal ToDecimal(this object value) {
if (null == value)
return 0.00m;
try {
return Convert.ToDecimal(value, CultureInfo.InvariantCulture);
}
catch (FormatException) {
return 0.00m;
}
}
...
// return me a decimal, please
decimal d = "1799.00".ToDecimal();
// when printing decimal, use Turkish culture
Console.Write(d.ToString("N", CultureInfo.GetCultureInfo("tr-TR")));
您可以将土耳其文化指定为整个线程的默认文化:
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR");
...
// now you don't have to mention Turkish culture
// ...but still have to specify the format
Console.Write(d.ToString("N"));
关于c# - 使用扩展方法将字符串转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508728/