How to convert a string containing an exponential number to decimal and back to string

左心房为你撑大大i 提交于 2019-12-05 20:49:28

To convert strings to numbers, as you already figured out, you just use a double. I'd try a different conversion though:

double myNum = double.Parse("<yournumber>", NumberStyles.AllowExponent | NumberStyles.Float, CultureInfo.InvariantCulture);

AllowExponent and Float should keep the notation, and InvariantCulture takes care of the decimal divider (which might not be a dot depending on the locale).

You can output scientific notation numbers via string.Format(), like this:

double num = 1234.5678; // 1.2345678e+03
string.Format("{0:e}", num); // should output "1.2345678E+03"

If you have to distinguish between numbers with and without the "E+xx" part, you'll have to search for it before converting the string to double, and a full snippet (WARNING: not tested!) could look like:

string myString = ReadNumberFromFile(); // Just a placeholder method
double myNum = double.Parse(myString, NumberStyles.AllowExponent | NumberStyles.Float, CultureInfo.InvariantCulture);
string output = string.Empty; //this will be the "converted-back number" container
if (myString.IndexOf("e", StringComparison.OrdinalIgnoreCase) >= 0)
{
    //Number contains the exponent
    output = string.Format("{0:e}", num); // exponential notation 'xxxExx' casing of 'e' changes the casing of the 'e' in the string
}
else
{
    //TODO: Number does NOT contain the exponent
    output = string.Format("{0:f}", num); // fixed-point notation in the form 'xxxx.xxx'
}

The point here is that, as far as number go, being with or without an exponent doesn't make any difference whatsoever, it's just a matter of representation (and it makes little sense to distinguish between them: it's really the same thing).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!