2012-07-23 48 views
2

我想在这里解析一个使用加蓬货币格式的数字。Double.Parse使用特定文化

格式使用“。”为组分隔和没有小数。

下面是一个例子:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Globalization; 
using System.Threading; 

namespace ConsoleApplication4 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      CultureInfo ci = new CultureInfo("fr-FR"); 

      ci.NumberFormat.CurrencyGroupSeparator = "."; 
      ci.NumberFormat.CurrencyDecimalDigits = 0; 
      ci.NumberFormat.CurrencySymbol = "CFA"; 

      Thread.CurrentThread.CurrentCulture = ci; 
      Thread.CurrentThread.CurrentUICulture = ci; 

      double.Parse("300.000", ci).ToString("C"); 
        // gives me a FormatException 
     } 
    } 
} 

有什么我失踪?

+3

您的评论不完整。目前还不清楚你期待什么,你得到了什么。我会说,你应该使用'decimal'而不是'double'作为货币值... – 2012-07-23 20:20:06

+0

我试图用加蓬语使用的格式来解析它。尽管我无法解析它,但我总是在'double.Parse'部分得到一个异常。 – Erick 2012-07-23 20:49:14

+0

我添加了Robert的行,我可以在控制台应用程序中解析。这不是使用MVC的ModelBinder,但我想这是一个开始。 – Erick 2012-07-23 20:53:01

回答

1

add this: ci.NumberFormat.NumberGroupSeparator =“。”;

3

就你而言,你必须帮助.NET一点点 - 当仅仅使用Parse时,它假设你想得到一个数字。法国文化使用,作为小数点分隔符,这就是您的代码抛出异常的原因。

试试这个,而是:

double.Parse("300.000", NumberStyles.Currency, ci).ToString("C"); 

现在,该字符串将被正确解析为货币,尊重您在ci文化规定的货币规则。

而且正如其他人所说的,在处理货币时你应该真的使用decimal。双是简单的not precise enough

+0

+1,但OP仍应使用小数点作为货币值。 – 2012-07-23 20:25:02

+0

@MareInfinitus同意,我相应地编辑了我的问题。 – 2012-07-23 20:28:47

相关问题