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:
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)
//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;
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.