Converting String to Double in C#

Converting String to Double in C#

Converting a string to double might be a very challenging task in programming environments when you consider different culture settings. Most of the time you deal with "." (dot) or "," (comma) as a decimal seperator.

Here are the simplest solutions for you to convert string values to double in c# programming language.

Converting known string values to double in c#

First example tries to read as an invariant culture element:

double.Parse("3.5", CultureInfo.InvariantCulture);

However, we recommend you to use TryParse method for better programming experiences.

double temp = 0;
double
.TryParse("3.5", NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out temp);

A generalized string to double converter in c#

However, your double may use another number decimal seperator. In this case, writing a Double Parser may solve your issue:

public static double GetDouble(string value, double defaultValue)
{
    double result;

    //Try parsing in the current culture
    if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&

        //Then try in US english
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&

        //Then in neutral language
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
    {
        result = defaultValue;
    }

    return result;
}


Converting String to Double in C#
added 10 years 8 months ago

Contents related to 'Converting String to Double in C#'

How to change number decimal seperator in C#?: This document explains how to change the number decimal seperator of the double and floating points in c# applications.

How to change DateTime format in C#: Changing the format of DateTime in C# applications.

- How to make bold the text before colon character in Microsoft Word
- Generate object from xml in c#
- 24 Useful Distinct Color Codes
- How to draw an arrow with DrawLine command
- How to write Snake game in C#?
- Break Parallel Foreach Earlier
- How to find all Stored Procedures having a given text inside
- How to Create and Write Excel File in C#
- Extension Methods
- Microsoft Code Contracts
- VersaFix
- QuickFIX
- fix4net
- Converting String to Double in C#
- C# File Operations, C# Input Output (C# I/O)
2
1