简体   繁体   English

C#:如何显式设置Double.Parse(字符串num)的区域性

[英]C#: how to explicitly set culture for Double.Parse(string num)

I download one program that read file and then parse double values from String to Double. 我下载了一个程序,该程序读取文件,然后将Double值从String解析为Double。 But I get an exception because this file contains numbers with '.' 但我得到一个例外,因为此文件包含带'。'的数字。 separator, but there is ',' in my culture. 分隔符,但在我的文化中有“,”。 How can I set culture explicitly? 如何明确设定文化?

You would use the Parse overload that accepts an IformatProvider . 您将使用接受IformatProviderParse重载。

Double.Parse("23.56", new CultureInfo("..."))

If you don't know the culture used to write the file you create a NumberFormatInfo and configure it as you like: 如果您不知道用来编写文件的区域性,则可以创建NumberFormatInfo并根据需要进行配置:

var nfi = new NumberFormatInfo();

nfi.NumberDecimalSeparator = ".";

var d = Double.Parse("23.56", nfi);

this was i'm used to do but i think i will use the NumberFormatInfo in the future ! 这曾经是我的习惯,但我认为将来我会使用NumberFormatInfo!

CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

try
{
   if (Thread.CurrentThread.CurrentCulture != null) 
   {
     double d = Double.Parse("23.5");
   }
}
finally
{
   Thread.CurrentThread.CurrentCulture = oldCulture;
}

Also usable: 也可以使用:

double.Parse((""+s).Replace(",","."), System.Globalization.CultureInfo.InvariantCulture)

Ugly as hell, but that's .Net... :) 丑陋的地狱,但这就是.Net ... :)

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

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