Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

double - c# Convert.ToDouble format exception error

I'm trying to convert this string to double

Convert.ToDouble("1.12");

and this is the output

System.FormatException was unhandled.

Should I do something like this?

    public static double ConvertToDouble(string ParseVersion)
    {
        double NewestVersion;
        try
        {
            NewestVersion = Convert.ToDouble(ParseVersion);
        }
        catch
        {
            ParseVersion = ParseVersion.Replace('.', ',');
            NewestVersion = Convert.ToDouble(ParseVersion);
        }

        return NewestVersion;
    }

    ConvertToDouble("1.12");

Or is there an easier solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

double.Parse will use the current culture by default. It sounds like you want the invariant culture:

double d = double.Parse("1.12", CultureInfo.InvariantCulture);

EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...