简体   繁体   中英

How to parse double in scientific format using C#

I have numbers outputted from a FORTRAN program in the following format:

 0.12961924D+01

How can I parse this as a double using C#?

I have tried the following without success:

// note leading space, FORTRAN pads its output so that positive and negative
// numbers are the same string length
string s = " 0.12961924D+01";
double v1 = Double.Parse(s)
double v2 = Double.Parse(s, NumberStyles.Float)

I would first do some manipulation of this string to get it from FORTRAN to .NET formatting:

  • Trim any leading space; if the negative sign is there we want it but we don't want spaces.
  • Replace "D" with "E".

The below should get you what you need:

string s = " 0.12961924D+01";
s = s.Trim().Replace("D", "E");
//s should now look like "0.12961924E01"    
double v2 = Double.Parse(s, NumberStyles.Float);

这应该有所帮助: s = s.Replace(' ', '-').Replace('D', 'E');

Since everyone else suggests replacing the space with a minus sign, which seems crazy, I'll offer this somewhat simpler solution:

string input = " 0.12961924D+01";
double output = Double.Parse(s.Replace('D', 'E'));

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