C# - Unexpected results when converting a string to double - c#

I have a string with value "20.616378139" and when i try to convert using Convert.ToDouble or Double.Parse i get 20616378139.0 insted of the right value.
Why is this happening and how should I fix it?

You probably live in a part of the world where the decimal point is written as a comma. Fix:
var str = "20.616378139";
var dbl = double.Parse(str, System.Globalization.CultureInfo.InvariantCulture);

There's an overload to the Parse method that provides an options parameter of some kind; this is the way that you can specify for it to handle scientific notation, etc. Try setting that explicitly. If that works, then look at the default culture info settings you are using.

I've used this command and there is no problem for me before.
string s = "20.616378139";
double d = Convert.ToDouble(s);
![enter image description here][1]

Related

C# float to string separator

I am new to C # and I am currently having problems with the following. In C #, I have a Pi floating point number and I want to convert it to a string using the ToString() method. But the conversion gives a string result with a comma "3,1415". On another machine, the same gives the string result with the dot "3.1415". What is the reason for this and what should I do to get a dotted string result?
EDIT: The problem is, I can't change the code, but I can install and uninstall .Net frameworks, change my OS settings, etc.
Edit: if you can't change the code. Change the language/localization of the system to one which uses dot as decimal separator. In Control Panel or Settings.
You should look at internationalization and localization in the System.Globalization namespace.
The advice here is to use one CultureInfo specific for parsing numbers or writing numbers to string.
var flt = 232.23f;
var str = flt.ToString(CultureInfo.InvariantCulture); //for example, you can use CultureInfo.CurrentCulture
This allows you to keep the ThreadCulture without change it.
But take a look at this link https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=net-5.0 .Take your time, is dense.
I would just set the current culture at the entry point of your program.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
However I would also check the regional settings and so forth on the machine where the comma separator appears.
It is related with current culture info. You can specify the culture info in ToString method as a parameter like;
var convertedFloat = floatVariable.ToString(new CultureInfo("en-GB"));
Thanks to GSerg, for comment about Windows regional settings. That solves my problem. In the Windows Control panel enter Region and Language. In the Formats tab click Additional Settings and in the Decimal symbol field specify what decimal separator must be used when converting a floating point number to a string.

Coded UI Test replacing string of ints with double

I'm writing a test for a webpage and I'm replacing some values from the recorded steps with csv values.
The problem is in the record I got this value:
public string UITboxNDocEditText = "866700228007551009280449220150921009003761527571";
and in the csv I got this value:
866700000007551009280449220150921009000001527571
the line I'm using to replace the value is this one:
this.UIMap.InsBDFParams.UITboxNDocEditText = TestContext.DataRow["n_b"].ToString();
the problem is that the script is instead writing this value : 8,66700000007551E+47
I tried casting the TestContext.DataRow line to a string instead of using the .ToString() method like this : (string)TestContext.DataRow["n_b"]; but got an error complaining about casting from a double so I assume the script is considering my value to be a double.
Any tips ?
You can use a format specifier to format the string, F0, the 0 stands for zero decimal places:
this.UIMap.InsBDFParams.UITboxNDocEditText =
((double)TestContext.DataRow["n_b"])
.ToString("F0");
Found out that encapsulating 866700000007551009280449220150921009000001527571 with double quotes solved the issue :
"866700000007551009280449220150921009000001527571".
I think it treats it as a string so it doesn't mess up the numbers.

How to parse from String to Float in C#?

This issue should be very simple but I can't find the way to make it work. I have the following code:
string yeah = "0.5";
float yeahFloat = float.Parse(yeah);
MessageBox.Show(yeahFloat.ToString());
But the MessageBox shows "5" instead of "0.5". How can I resolve this using float?
float yeahFloat = float.Parse(yeah, CultureInfo.InvariantCulture);
See documentation: http://msdn.microsoft.com/en-us/library/bh4863by.aspx
0.5 is the way some country are writing decimal number, like in America. In France, decimal number are more written with a comma : 0,5.
Typically, the code you give throw an exception on my computer.
You need to specify from what culture you are expected the string to be parse. If not, it will take your computer culture setting, which is bad, since your code could run in different countries.
So, by specifying an invariant culture, you said to the Parse function : ok, let's try to parse point or comma, try as hard as you can:
string yeah = "0.5";
float yeahFloat = float.Parse(yeah, CultureInfo.InvariantCulture);
Console.Write(yeahFloat);
There is a lot of question already on this subject :
Parse string to float number C#
Best way to parse float?
C# parsing float from string
etc..
By default, Single.Parse(String) parses based on your localization settings. If you want to use a specific one, you'll have to use an appropriate overload of that method with the culture settings that you want.
You can try this with float.TryParse() :
string yeah = "0.5";
float yeahFloat;
if (float.TryParse(yeah,System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,out yeahFloat))
{
MessageBox.Show(yeahFloat.ToString());
}
Try passing the formatting you require in the ToString() method
MessageBox.Show(yeahFloat.ToString("0.0")); // 1 decimal place

c# string format

How do I get the output of this to read 0 instead of 00 when the value is 0?
String.Format("{0:0,0}", myDouble);
string.Format("{0:#,0}", myDouble);
(tested version)
String.Format("{0:#,0}", myDouble);
Another alternative is to use this:
string s = string.Format("{0:n0}", myDouble);
If you always want commas as the thousands separator and not to use the user's locale then use this instead:
string s = myDouble.ToString("n0", CultureInfo.InvariantCulture);
While the posted answers here ("{0:#,0}") are correct I would strongly suggest using a more readable picture (also to avoid confusion about decimal/thousand separators):
string.Format("{0:#,##0}", v); // to print 1,234
string.Format("{0:#,##0.00}", v); // to print 1,234.56
But all those pictures work the same, including 2 comma's for 1e6 etc.

Converting string to float throws error "Incorrect format"

I can't get my application to convert a string into a float:
float number = float.Parse(match);
Where match is "0.791794".
Why doesn't this work? The error I get is "Input string was not in a correct format.", but I can't understand what's wrong with it.
Try passing a culture object (i.e. InvariantCulture, if this is system-stored data and the format won't ever be different) to the overload that accepts one; your current culture may be set to something that expects a comma as the separator instead of a period (or similar).
You could also try
string x = (0.791794f).ToString()
just to see what it prints out.
Checking CultureInfo.CurrentCulture might be instructive as well.
(Also, sanity check -- I assume those quotes are from you, and not part of the string value themselves?)
Are you sure match is a string type? You may need to typecast it.
Seems to work fine in 2008
static void Main(string[] args)
{
var match = "0.791794";
float number = float.Parse(match);
Console.Out.Write(number);
}
You migth try restarting vs.
Hope that helps

Categories

Resources