Failed to Parse string to float in C# - c#

I want to convert the following string to "5,28" to float number, I used this code but I got false result. Also I'm setting the device language to french.
Is there something I'm missing? I have tried to convert the string to different culture like CultureInfo("en-US") but still did not work.
bool result = float.TryParse("5,28", NumberStyles.Float,
CultureInfo.InvariantCulture.NumberFormat, out number);

InvariantCulture uses . as a NumberDecimalSeparator not ,
Since you forced to use Float style, this style includes only AllowDecimalPoint in a separator styles, your method thinks this , is a decimal separator but InvariantCulture does not use it. That's why you get exception.
There are a few things you can do. One option can be Clone an InvariantCulture, set NumberDecimalSeparator property to , and use that cloned culture in your TryParse method.
float f;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.NumberDecimalSeparator = ",";
var result = float.TryParse("5,28", NumberStyles.Float, clone, out f); // true
Or you can use a culture that already has , as a NumberDecimalSeparator like tr-TR culture.1
float f;
var result = float.TryParse("5,28", NumberStyles.Float,
CultureInfo.GetCultureInfo("tr-TR"), out f); // true
1:Since I'm from Turkey :)

The reason that the value 5,28 does not parse is that invariant culture uses decimal dot ., not decimal comma.
To solve this problem you could either replace comma with a dot, like this
bool result=float.TryParse(
"5.28"
, NumberStyles.Float
, CultureInfo.InvariantCulture.NumberFormat
, out number);
or replace CultureInfo.InvariantCulture for a culture that uses comma in place of a dot:
bool result=float.TryParse(
"6,78"
, NumberStyles.Float
, new CultureInfo("de-DE").NumberFormat
, out number);
Demo.

Related

Would there be a better way of doing this?

post.Min.ToString("0.00").Replace(",", ".").Replace(".00", string.Empty)
post.Min is a double such as 12,34 or 12,00. Expected output is 12.34 or 12.
I basically want to replace the comma by a point, and cut the .00 part if any.
I am asking because I couldn't find anything, or because I don't exactly know what to search. This has an high change of being a duplicate, I simply can't find it. Please let me know.
The simplest solution would appear to be to use CultureInfo.InvariantCulture, and I reject the suggestion that this is any more complicated than using a series of replaces as you demonstrated in your question.
post.Min.ToString("0.##", CultureInfo.InvariantCulture);
# is the digit placeholder, described as the docs like this:
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Try it online
If you use this in a lot of places, and that's why you want to keep it simple, you could make an extension method:
public static class MyExtensions
{
public static string ToHappyString(this double value)
{
return value.ToString("0.##", CultureInfo.InvariantCulture);
}
}
And then you just have to call .ToHappyString() wherever you use it. For example, post.Min.ToHappyString()
You can use .ToString("0.##").
like,
// Considered german culture; May be this is your current culture
CultureInfo culture = new CultureInfo("de");
double number1 = Double.Parse("12,34", culture);
double number2 = Double.Parse("12,00", culture);
Console.WriteLine(number1.ToString("0.##"));
Console.WriteLine(number2.ToString("0.##"));
Output:
12.34
12
.Net fiddle
Checkout the ToString overloads article on MSDN about examples of the N format. This is also covered in the Standard Numeric Format Strings article.
Relevant examples:
// Formatting of 1054.32179:
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322
For the dot instead of comma to do it properly, in combination with N0 use:
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
double.ToString("0.##") to consider decimal places only if not .00 and you can create your own Number Format without using Culture:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
post.Min.ToString("0.##", nfi);

Strange output when converting string to double

I already searched for my problem but I wasn't successfully and that's the reason I'm here.
All I want to do is reading a string like "3.14" and convert it to double.
Enough said... here is my code:
using System;
namespace GlazerCalcApplication
{
class MainClass
{
public static void Main (string[] args)
{
string heightString;
double height;
heightString = Console.ReadLine();
height = Convert.ToDouble(heightString);
Console.WriteLine(height);
}
}
}
Output:
3.14
314
Press any key to continue...
Why is my double value not 3.14?
Instead of Convert.ToDouble() I also tried it with double.Parse() but I received the same behaviour. Reading strings like 3,14 is no problem.
Maybe I should also mention that I use MonoDevelop and a linux OS.
Thanks in advance.
Try specifying the culture as Invariant:
height = Convert.ToDouble(heightString,CultureInfo.InvariantCulture);
It seems the decimal seperator of your culture is comma instead of dot therefore dot is truncated after conversion.
Convert.ToDouble(string) uses Double.Parse(string, CultureInfo.CurrentCulture) method explicitly.
Here how it's implemented;
public static double ToDouble(String value) {
if (value == null)
return 0;
return Double.Parse(value, CultureInfo.CurrentCulture);
}
It is likely your CurrentCulture's NumberFormatInfo.NumberDecimalSeparator property is not . (dot). That's why you can't parse a string with . as a date seperator.
Example in LINQPad;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator.Dump(); // Prints ,
As a solution, you can create a new reference of your CurrentCulture and assing it's NumberDecimalSeparator property to . like;
double height;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator = ".";
height = Convert.ToDouble("3.14", c);
Judging by the result I take it you are in a culture zone where comma is the normal decimal separator.
Also, I take it that you want both dot and comma to be used for decimal separation.
If not, the below is not the proper solution.
The fastest solution for using both would be
height = Convert.ToDouble(heightString.Replace('.', ',');
This would mean that both dots and comma's are used as comma and thus parsed as a decimal separator.
If you only want to use a dot as separator, you can use invariantculture or a specific numberformatinfo. Invariant culture is already shown in the other posts. numberformat info example:
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString,nfi);
For completeness, the example below shows both using numberformatinfo for setting the dot as decimal separator, as well as replacing comma with dots, so both characters are used for decimals
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString.Replace(',', '.'),nfi);
Different .Net cultures (countries) have different decimal separators.
If you expect input values to be in some specific format - either use some particular culture or InvariantCulture. Also consider using double.Parse as it geve more flexibility on parsing the values than generic Convert.ToDouble.
var d = double.Parse(heightString, CultureInfo.InvariantCulture);
If you expect user to enter value in local format - your code is fine, but either your expectation of "local format" is wrong, or "current culture" set incorrectly.

Double.Parse for Native language support

I have a value 20,55 which is in German language.
When I change the regional settings to US the value gets displayed as 2055.0 after running this code:
double d = Double.Parse("20,55",CultureInfo.CurrentCUCulture);
Why is that?
Because in US the , is the thousand separator and it's ignored? In the same way that in Germany (and continental Europe) the . is the thousand separator and it's ignored?
In Germany you write: 1.000,55. In USA you write: 1,000.55 (and there are some schools of thought that remove the , if there is a single digit before. So 1000.55 and 11,000.55).
Now, if you want to be sure your program is using the de-DE culture, pass as a parameter everywhere
CurrentCulture culture = new CultureInfo("de-DE");
double d = double.Parse("20,55", culture);
In the US, the decimal separator is ., not ,. If you attempt to parse 20,55, it will (apparently) ignore the commas as standard triplet separators (such as in 1,234,567.89), even though there aren't three digits in all of them.
If you want to parse a Euro-style number, you need to parse it with a Euro-style culture setting.
It's because the US decimal separator is the . and not the ,.
If you want to avoid that problem no matter the regional settings of the user, you could write a extension method:
public static String ToRegionalNumber(this String str) {
String regionalNb = str.Replace(",", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
regionalNb = regionalNb .Replace(".", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
return regionalNb ;
}
And call this method when working with your number:
double d = Double.Parse("20,55".ToRegionalNumber());

Double.TryParse() input decimal separator different than system decimal separator

I have a source XML that uses a dot (".") as a decimal separator and I am parsing this on a system that uses a comma (",") as a decimal separator.
As a result, value of 0.7 gets parsed with Double.TryParse or Double.Parse as 7000000.
What are my options to parse correctly? One of them is to replace dots in source with commas with String.Replace('.', ',') but I don't think I like this very much.
XML standard is explicit about the formatting of dates and numbers etc. This helps to ensure that the XML is platform independent and interoperable. Take a look at using XmlConvert for xml data.
double value = XmlConvert.ToDouble(stringValue);
This does the job:
string test = "0.7";
Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));
double.TryParsehas an overload taking an IFormatProvider. Use a coresponding CultureInfo, in your case CultureInfo.InvariantCulture can be used.
Easy way to specify custom decimal separator:
var price = "122$00";
var nfi = new NumberFormatInfo { CurrencyDecimalSeparator = "$" };
var ok = decimal.TryParse(price, NumberStyles.Currency, nfi, out result);

double.TryParse in dutch

Web server running in Dutch(Belgium)
double output;
double.TryParse(txtTextbox1.Text, out output);
Is this a good way to convert text to double in dutch environment? Let's say the input is "24.45" instead of "24,45"
If you want to use the Dutch (Belgium) number format:
double output;
double.TryParse("24,45", NumberStyles.Any, CultureInfo.GetCultureInfo("nl-BE"), out output);
Or to use the US number format:
double output;
double.TryParse("24.45", NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out output);
If you attempt to parse "24.45" with a Dutch culture set, you'll get back "2445", similarly, if you attempt to parse "24,45" with a US culture, you'll get "2445". If you want the parse to fail if the wrong decimal point is used, change NumberStyles.Any to exclude the flag: NumberStyles.AllowThousands:
double output;
if (double.TryParse("24.45", NumberStyles.Any ^ NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("nl-BE"), out output))
If your entire application is in Dutch, you should change your cultureinfo globally - here's how to do it in WinForms and here's how to do it in ASP.NET.
Once you're using a globally set CultureInfo, you can change the above code to:
double output;
double.TryParse("24.45", NumberStyles.Any, CultureInfo.CurrentCulture, out output);
The correct Culture Code for dutch-Belgium is "nl-BE", so you should use that instead of the often suggested "nl-NL", which would give you the variant of Dutch culture settings appropriate for the Netherlands.
double output;
double.TryParse("24.45", NumberStyles.Any, CultureInfo.GetCultureInfo("nl-BE"), out output);
You can find a complete list of Culture Codes at http://arvindlounge.spaces.live.com/blog/cns!C9061D5B358A2804!263.entry .
You should set the culture to Dutch. The culture is what determines how strings representing numbers are parsed.
Check this article: HOW TO: Set Current Culture Programmatically in an ASP.NET Application, it explains both how to set the culture for the ASP.NET application and for the current thread.
If your server's regional settings are set to Dutch numbers, try this:
double output;
double.TryParse(txtTextbox1.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out output);
You can use the overload that allows you to specify locale (sample with Swedish locale, since I know how that one works):
double result;
if (double.TryParse("24,95", NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("sv-SE"), out result))
{
Console.WriteLine(result.ToString());
}
If I would pass "24.95" in the above call to TryParse it would return false, since the Swedish decimal sign is ",".
You may want to experiment with the NumberStyles parameter to get the exact behaviour that you want. For instance, if I would change to NumberStyles.Any and call the method with the input 24.95 above, TryParse returns true and the result will be 2495, which might not be what you want.
My version works fine with both separators '.' and ',':
public static double? GetDoubleFromString(string strNum)
{
double num = 0;
strNum = strNum.Replace(',', '.');
if (double.TryParse(strNum, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out num))
return num;
return null;
}

Categories