简体   繁体   中英

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. 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 .

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:

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 !

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... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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