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;
}
Related
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);
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.
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.
This might be a simple and basic question, but, thought of confirming with you. Im in the process of writing code to validate the entered text information is double or not. In my code, below is the line to validate the speed value taken from a text box.
double _mSpeed = 0.0;
if (!Double.TryParse(txtboxSpeed.Text, out _mSpeed))
throw new Exception("Input value for Speed is invalid !!!");
But, if user provides 4.4.4 in speed text box, TryParse is parsing the text string to 444.0 value. Im wondering this is correct or not. Please share your thoughts whether if user enters any value with 2 decimal points, should it not parse to double or what is the expected behavior.
In cultures where . is the decimal separator, like en-US and the invariant culture, 4.4.4 is not valid. In other cultures, like de-DE, , is the decimal separator and . is the thousands separator, so 4.4.4 is 444 (with nonstandard, but acceptable, thousands separators inserted, like 4,4,4 in the en-US culture).
double.Parse("4.4.4", new CultureInfo("de-DE")) // 444
double.Parse("4.4.4", new CultureInfo("en-US")) // FormatException: Input string was not in a correct format.
double.Parse("4,4,4", new CultureInfo("en-US")) // 444
double.Parse("4,4,4", new CultureInfo("de-DE")) // FormatException: Input string was not in a correct format.
The issue could be that the Culture currently used by your application treats comma as decimal separator instead of period. You can force it to use period as decimal separator by setting culture to en-GB.
double _mSpeed = 0.0;
if (!Double.TryParse(txtboxSpeed.Text,NumberStyles.Any,CultureInfo.CreateSpecificCulture("en-GB"), out _mSpeed))
throw new Exception("Input value for Speed is invalid !!!");
Instead of creating a CultureInfo for a specific culture that uses your number format (e.g., "en-US"), you can also just specify NumberFormatInfo.InvariantInfo.
double val1, val2;
bool b1 = double.TryParse("4.4.4", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out val1);
bool b2 = double.TryParse("4,444.4", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out val2);
In the above code b1 is set to false but b2 succeeds and val2 is 4444.4.
Hi i m using given below method to convert in to string its working fine chrome but in IE its through exception Input string was not in a correct format. at this line
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
these are values i m passing to it
600, 298.8, 65505, 69, 70, 20.5, 20.5, 20.5, 20.5, 1840.4, 682, 1040.3
in chrome its working but in IE it gives exception on second value when i change the culture to french language please help me out what is the problem
public static String ConvertTimeToString(this string time)
{
if (String.IsNullOrEmpty(time))
{
return time;
}
TimeSpan s;
if (time.IndexOf(':') >= 0)
{
s = TimeSpan.Parse(time);
}
else
{
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
}
return s.ConvertTimeToString();
}
The failure is probably in the call Convert.ToDouble. Your code probably executes in a CultureInfo that has ',' as decimal separator, but your values use '.'. I would advice you to use Double.TryParse using a CultureInfo that has '.' as decimal separator instead:
Double value;
if (Double.TryParse(time, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out value))
{
s = TimeSpan.FromSeconds(value);
}
You need to specify an IFormatProvider when you use Convert.ToDouble(time):
Convert.ToDouble(time, CultureInfo.InvariantCulture)
Specifying CulturInfo.InvariantCulture specifies a culture that expect floating points written as 1.234 (note the period). The source of your problem may be that you time is in the format 1,234 (note the comma). Or maybe it is the reverse: You don't specify an IFormatProvider and the current culture of you ASP.NET process uses comma as a decimal separator, but the string provided uses period?
If the decimal point used isn't consistent you should either fix it at the source (not sure what the source is here) or as a last resort you can replace comma by period:
Convert.ToDouble(time.Replace(",", ".") , CultureInfo.InvariantCulture)
However, trying to parse a string and not knowing the what to expect is not the best thing to do.