Convert String into Double - Result is failing [duplicate] - c#

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).

Related

Problem in converting string into double in C# [duplicate]

This question already has answers here:
String to decimal conversion: dot separation instead of comma
(8 answers)
Closed 6 months ago.
I need a program that takes two inputs from the user and perform a calculation. Those inputs need to be double datatype.
The problem I'm facing is that: the program receives a decimal value with dot separator, but when converting it to double, it loses the decimal value. For example, input from the user is 2.5, but when converting it becomes 25.
When the user type 2,5 it is correctly converting it to 2.5
Here's my code example:
Console.WriteLine("Var1: ");
string? v1 = Console.ReadLine();
Console.WriteLine("Var2: ");
string? v2 = Console.ReadLine();
double v1Double = Double.Parse(v1);
double v2Double = Double.Parse(v2);
Console.WriteLine($"Var1: {v1Double}");
Console.WriteLine($"Var2: {v2Double}");
Console.WriteLine($"Multiplication: {v1Double * v2Double}");
Here's what I'm getting when with dot separator:
Here's what I'm gettig when comma separator:
Can anyone help me how to address this problem?
You could use NumberFormatInfo for this problem like so:
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
double doubleVal = Convert.ToDouble(YOUR_STRING, provider);

Converting string to double exception [duplicate]

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.

string to double parsing error

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

Decimal Casting

I have a decimal number like this:
62.000,0000000
I need to cast that decimal into int; it will always have zero decimal numbers; so I wont loose any precision. What I want is this:
62.000
Stored on an int variable in c#.
I try many ways but it always give me an error, that the string isn't in the correct format, this is one of the ways i tryied:
int.Parse("62.000,0000000");
Hope you can help me, thanks.
You need to parse it in the right culture. For example, the German culture uses "." as a group separator and "," as the decimal separator - so this code works:
CultureInfo german = new CultureInfo("de-DE");
decimal d = decimal.Parse("62.000,0000000", german);
int i = (int) d;
Console.WriteLine(i); // Prints 62000
Is that what you're after? Note that this will then fail if you present it with a number formatted in a different culture...
EDIT: As Reed mentions in his comment, if your real culture is Spain, then exchange "de-DE" for "es-ES" for good measure.
You need to specify your culture correctly:
var ci = CultureInfo.CreateSpecificCulture("es-ES");
int value = (int) decimal.Parse("60.000,000000", ci);
If you do this, it will correctly convert the number.
Why don't you just cast it to int instead of parsing?

parsing float into string

I have a number like so: 4.47778E+11
Can anyone give me a way of converting that into its number representation easily in c#?
Thanks
string s = "4.47778e+11";
double d = double.Parse(s);
or
string s = "4.47778e+11";
if (double.TryParse(s,out d))
{
// number was parsed correctly
}
or for internationalization
double.Parse("4.47778e+11", System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
Try this MSDN thread. It's called scientific notation by the way, and a quick google normally solves simple issues.
That's assuming you mean parsing from a string to a float, your question & title are conflicting
Use
float num = Convert.ToFloat(Convert.ToDouble(s));
But you still lose precision, floats are only precise to 7 digits, so you're better off using just the Convert.ToDouble() (precise to 15 or so digits), so you won't lose any digits in your example.
Use Convert:
double value = Convert.ToDouble("4.47778E+11");

Categories