c# - 使用扩展方法将字符串转换为十进制

标签 c#

我的字符串是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/

相关文章:

c# - ASP.NET Web API IExceptionLogger 不捕获异常

c# - Entity Framework Core 中的自引用多对多关系

c# - 确保 NLOG 确实进行日志记录?

c# - 打印具有自定义行的数据表

c# - 导出到 excel 数据时出错 : ' ' , 十六进制值 0x07,是使用 c# 的无效字符

c# - Docker 中的剧作家不工作 : Microsoft. Playwright.PlaywrightException:可执行文件不存在

c# - 这 2 个 LINQ 连接查询实现相同的效果吗

c# TempData 等效于 php

c# - 无法在 Windows 7 上使用 WellKnownSidType.WorldSid 添加访问规则

c# - ASP.NET Web 应用程序找不到我的 XML 文件,说它不在 IIS Express 文件夹中