简体   繁体   中英

C# converting a string to double

I am trying to convert a string to double but unable to do so...

I tried to simulate a dummy code which is part of my application, the text value comes from a 3rd party application on which i dont have control.

I need to convert the string which is represented in a general format "G" to a double value and show that in a text box.

        string text = "G4.444444E+16";
        double result;

        if (!double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
        {
        }

I tried by changing the numberstyles and cultureinfo but still the result is always returns 0. Suggest what is wrong with the code?

Just get rid of this "G"

    string text = "G4.444444E+16";
    string text2 = text.SubString(1); // skip first character
    double result;

    if (!double.TryParse(text2, NumberStyles.Any,
        CultureInfo.InvariantCulture, out result))
    {
    }

Here is more details:

        Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");

        // if input string format is different than a format of current culture
        // input string is considered invalid, unless input string format culture is provided as additional parameter

        string input = "1 234 567,89"; // Russian Culture format
        // string input = "1234567.89"; // Invariant Culture format

        double result = 9.99; // preset before conversion to see if it changes
        bool success = false;

        // never fails
        // if conversion is impossible - returns false and default double (0.00)
        success = double.TryParse(input, out result);
        success = double.TryParse(input, NumberStyles.Number, CultureInfo.InvariantCulture, out result);

        result = 9.99;
        // if input is null, returns default double (0.00)
        // if input is invalid - fails (Input string was not in a correct format exception)
        result = Convert.ToDouble(input);
        result = Convert.ToDouble(input, CultureInfo.InvariantCulture);

        result = 9.99;
        // if input is null - fails (Value cannot be null)
        // if input is invalid - fails (Input string was not in a correct format exception)
        result = double.Parse(input);
        result = double.Parse(input, CultureInfo.InvariantCulture);

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