How to parse from String to Float in C#? - 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

Related

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.

Make Convert.ToDouble work with different CultureInfos

Whats the best way to make the conversion work when you have:
string a = "10.0123";
string b = "10,0123";
And the cultureinfo is either swedish or english, it needs to work with both.
I tried:
double aSwe = Convert.ToDouble(a, CultureInfo.GetCultureInfo("sv-SE"));
double bSwe = Convert.ToDouble(b, CultureInfo.GetCultureInfo("sv-SE"));
double aInv = Convert.ToDouble(a, CultureInfo.InvariantCulture);
double bInv = Convert.ToDouble(b, CultureInfo.InvariantCulture);
Since '.' is not a valid separator in Swe and ',' is not valid in Eng I dont know how to make it work with both using the same code.
Only solution I come up with is to replace the comma or dot before converting but it feels like there should be better solution?
You shouldn't try to make it work with both without any extra context.
It's like trying to parse "06/05/2010" as a date without any cultural information: it could mean the May 6th or June 5th.
Likewise "1,234" is either a value a bit more than a thousand, or a bit more than one: you need to know the cultural information in order to interpret it unambiguously.
So instead of trying to solve the problem of interpreting something without enough information, I suggest you focus on the problem of getting all the information you need (or changing the way you get your text data to always be in one particular format).

C# - Unexpected results when converting a string to double

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]

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

How to make doubles always contain a . character?

I noticed my doubles contain different precision characters depending on regional settings.
For example:
3,47 or 3.45
How can I enforce the double should always contain a . precision character?
Problem is once I serialize the class containing this double to XML, it gets shipped to other systems expecting a standard result.
So after reading your responses (and thanks), do you guys recommend changing the property to a string, (making the replacements in a string), so that it serializes with the string value (not the double)?
You need to put the double to string using the Invariant Culture.
double d = 3.47;
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
You will need to format with the InvariantCulture.
Note that the "." and "," formatting characters are interpreted according to the culture settings.
This little tutorial will be the answer you need, I expect:
http://www.java2s.com/Tutorial/CSharp/0440__I18N-Internationalization/Parsingnumberswithcultureinvariantparsing.htm
double.Parse(numberString, CultureInfo.InvariantCulture);
The double itself doesn't include a "." or a ",", only the print out of the representation does. You can read up on custom formats here.
[Update according to OP]
I don't know exactly what your design looks like, but it would probably be smart to create a string property on your DTO, which would output the formatted string of your double, and then mark your double property as not serializable.
When you need to do this for all numbers in your current applicaton, you can use the following to set it application-wide (new threads will inherit this setting):
// use this statement to force the default:
Application.CurrentCulture = CultureInfo.InvariantCulture;
string s = myNumber.ToString();
// for one number you have to remember to use:
string s = myNumber.ToString(CultureInfo.InvariantCulture);
Note: by default, your application, whether ASP.NET or WinForms, will use the culture settings of the system it is running on (in ASP.NET, you can set the culture globally in the web.config).

Categories

Resources