This question already has answers here:
Input string was not in a correct format #2
(10 answers)
Closed 9 years ago.
I am beginner in C#. I'm trying to convert a string to double. Here is the code with the method double.Parse():
static void Main(string[] args)
{
string s="0.5";
double b = double.Parse(s);
Console.WriteLine("double.Parse() - {0}",b);
}
I tried with System.Convert.ToDouble() too:
static void Main(string[] args)
{
string s="0.5";
double b = System.Convert.ToDouble(s);
Console.WriteLine("Convert.ToDouble() - {0}",b);
}
In both ways the Program throws Exception:
"Input string was not in a correct format".
Please help!!!. Thanks in advance.
As Sergey Berezovskiy commented, this is probably because your machine's culture uses , instead of . as the decimal separator. If you want to force it to use . (consider the implications) you must use parse using an invariant culture. At the bottom of this article there are a lot of examples on how to achieve this.
I think your current culture has ',' as the decimal separator, if that is the case, either use "0,5" instead of "0.5" or change the separator:
var s="0.5";
var culture = CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
var b = double.Parse(s, culture);
Console.WriteLine("double.Parse() - {0}",b);
Try that, and see if it fixes it.
Sergey is completely right.
Both Convert.ToDouble method and Double.Parse method use CurrentCulture as a default.
And looks like your current culture's NumberFormatInfo.NumberDecimalSeparator property is not . and that's why your code throws FormatException.
As a solution, you can set your NumberDecimalSeparator to . in your code before you parsing it.
CultureInfo c = CultureInfo.CurrentCulture;
c.NumberFormat.NumberDecimalSeparator = ".";
double b = Double.Parse(s, c); // Or Convert.ToDouble(s, c)
And by the way, using the Convert.ToDouble(String) method is equivalent to Double.Parse(String) method.
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);
This question already has an answer here:
Why does NumberStyles.AllowThousands work for int.Parse but not for double.Parse in this example?
(1 answer)
Closed 3 years ago.
having a string that's looking like "1.900,00". How could I format this string to a decimal of 1900?
Using:
decimal.TryParse("1.900,00", out var vkp)
Will give me a false result. How can I handle this?
Here's a URL to the online C# compiler: https://dotnetfiddle.net/B5EyyC
You could try using a CultureInfo that uses '.' as thousands separator and ',' as decimal separator (for example "de-DE"). And also the appropriate NumberStyles.
string input = "1.900,00";
decimal.TryParse(input,
NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("de-DE"), out var output);
You can even create your very own instance of NumberFormatInfo where you can specify the NumberDecimalSeparator and NumberGroupSeparator any way you like.
try this:
string s = "1.900,00";
s = s.Substring(0, s.LastIndexOf(",")).Replace(".", "") + "." + s.Substring(s.LastIndexOf(",") + 1);
decimal vkp = 0;
decimal.TryParse(s, out vkp);
I guess you could try the following:
string number = "1.900,00";
decimal.TryParse(number.Split(",")[0].Replace(".",""), out var vkp);
In case you need a more foolproof checking you could try making a function that checks whether or not the string contains a ',' character.
public static bool ToDouble(string s, out double d)
{
if (s.Contains(","))
return double.TryParse(s.Split(",")[0].Replace(".", ""), out d);
return double.TryParse(s, out d);
}
Also you can get the decimal separator of you localization settings via:
string dsep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
Decimal.TryParse doc
//using System.Globalization;
NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
CultureInfo culture = CultureInfo.CreateSpecificCulture("es-ES");
Decimal vkp;
Decimal.TryParse("1.900,00", style, culture, out vkp);
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 question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading a double value from a string
I have a problem with converting my String into a double, I always get strange results.
I want to convert the following string:
string Test = "17828.571428571";
I tried it like this (because it normally works):
Double _Test = Convert.ToDouble(Test);
Result is: 17828571428571 (without the dot, lol)
I need it as a double, to Math.Round() afterwards, so I have 17828 in my example.
My second idea was to split the string, but is that really the best method? :S
Thanks for helping me!
Finn
Use InvariantCulture
Double _Test = Convert.ToDouble(Test,CultureInfo.InvariantCulture);
EDIT: I believe your current culture is "German" de-DE, which uses , for floating point.
Tried the following code. You may also use NumberFormatInfo.InvariantInfo during conversion.
string Test = "17828.571428571";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
double d = Convert.ToDouble(Test);
double d2 = Convert.ToDouble(Test, CultureInfo.InvariantCulture);
double d3 = Convert.ToDouble(Test, NumberFormatInfo.InvariantInfo);
string Test2 = "17828,571428571"; //Notice the comma in the string
double d4 = Convert.ToDouble(Test2);
Console.WriteLine("Using comma as decimal point: "+ d4);
Output: (Notice the comma in the output)
Wihtout Invariant: 17828571428571
With InvariantCulture: 17828,571428571
With NumberFormatInfo.InvariantInfo: 17828,571428571
Using comma as decimal point: 17828,571428571
double _Test = double.Parse(Test,CultureInfo.InvariantCulture);
You need to set the format provider of the conversion operation to invariant.
Try Double.TryParse or Double.Parse if you are sure there is the correct format
EDIT: But take care of the format. as example if you are german you need to type 140,50 and not 140.50 because 140.50 would be 14050.
Or you pass as parameter that you dont care of culture (see other posts).
i have the following code:
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("mk-MK");
string s2 = "4.434,00";
double d;
if (Double.TryParse(s2, NumberStyles.Number, CultureInfo.CurrentCulture, out d))
{
//String.Format("{0:0.0,00}", d);
Console.WriteLine(d + " Type of: " + d.GetType());
}
else
{
Console.WriteLine("ne go parsirashe");
}
String.Format("{0:0.0,00}", d);
Console.WriteLine(d);
//Console.WriteLine(String.Format("{0:0,0.00}", d));
//Console.WriteLine(s2.GetType().ToString());
//Console.ReadLine();
//String.Format("{0:0.0,00}"
Console.ReadLine();
The output is: 4434 Type of: System.Double
4434
Why isn't the value of d in the format of : 4.434,00 ? Can you please help me with this? I've sent couple of hours trying to figure this out before trying to reach out to you guys. Thanks!!!
You are discarding your formatted string - you are not assigning it to a string and simply outputting the double to the console (which would call ToString() on it).
Try this:
string forDisplay = string.Format("{0:0.0,00}", d);
Console.WriteLine(forDisplay);
Or, even shorter:
Console.WriteLine(string.Format("{0:0.0,00}", d));
Update:
In order to format the string according to your culture, you will need to use the Format overload that takes an IFormatProvider (i.e. a culture) and ensure that the format string uses the right characters for the different parts (, for standard thousands separator and . for standard decimal separator - see here for the meanings of each such character in a format string):
var res = String.Format(CultureInfo.CurrentCulture, "{0:0,0.00}", d);
Console.WriteLine(forDisplay);
Result:
4.434,00
You meant to do:
string formatted = String.Format("{0:0.0,00}", d);
Console.WriteLine(formatted);
string.Format returns a string -- it cannot affect the formatting of a double, since doubles have no formatting at all. Doubles only store the raw numeric value (as bits, internally).
You have the . and , around the wrong way, if I'm understanding what you're trying to do.
If you read the Custom Numeric Format Strings page on MSDN, you can see that you need to use , for the thousands separator, and . for the decimal separator, and (the important part) the target culture is irrelevant here. The format is always the same, regardless of the current culture.
So what you want to use is:
Console.WriteLine("{0:0,0.00}", d);
Then the output is:
4434 Type of: System.Double
4.434,00