float.Parse problem (c#)

Hi there !

I’m trying to convert a string into a float in c#, actually it work, I got my float but i still got this error :

FormatException: Invalid format.
System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Double.cs:209)
System.Single.Parse (System.String s) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Single.cs:183)

here is my problematic line

LFOA = float.Parse(vvvvLFO.LFOa);

I tried to find documentation about the parse method in c# but only found stuffs about System.Globalization.NumberStyles.etc… and i didn’t really understood what was going on.

Does Anybody know what I should do about it ?

You won’t find anything under float.Parse or similar since float is an alias for the Single class, as in Single-precision floating point number. Similarly there is Double for double, Int32 for int, Int64 for long, and so on. The documentation for this function is found here. You’ll notice it shows the class and the function name being called in the error message.

What is the string you are trying to parse? I’m assuming it’s under the variable LFOa which is a member of the class vvvvLFO, but what is actually string’s value?

Strings could contains any data, and some of them cannot be converted to float. To avoid a lot errors use float.TryParse() method which returns true if convertation completed successfully.

    float LFOA = 0; /// default value
    if(float.TryParse(vvvvLFO.LFOa, out LFOA))
    {
    	/// everything is ok
    }
    else
    {
    	/// something wrong. vvvvLFO.LFOa has incorrect float value
    }

Or shorter:

    float LFOA = 0; /// default value
    if(!float.TryParse(vvvvLFO.LFOa, out LFOA))
    	;/// something wrong. vvvvLFO.LFOa has incorrect float value
1 Like
string myStr = "3.25";
vector3d myVector = new vector3d();
myVector.x = (float)double.Parse(myStr,System.Globalization.NumberStyles.AllowDecimalPoint);

I think this is what you’re looking for.

2 Likes

Seeing as we’re all chiming in, I’ll share my ToDouble and ToSingle methods in my ConvertUtil class. I do this to support hex values, and return a default value (0) if the conversion fails (standard I always stick to). I plan to support identifiers for other bases (I have a note on it), but haven’t written it yet. The hex values are expected in the format defined in the regex… so something like:

#FFAA0011

		private const string RX_ISHEX = "(?<sign>[-+]?)(?<flag>0x|#|&H)(?<num>[\\dA-F]+)$";
		
		/// <summary>
		/// Converts any string to a number with no errors.
		/// </summary>
		/// <param name="value"></param>
		/// <param name="style"></param>
		/// <param name="provider"></param>
		/// <returns></returns>
		/// <remarks>
		/// TODO: we need to allow all symbol types for hexadecimal values as well. Including fractional parts. This will require a lot more work. 
		/// I would also like to possibly include support for other number system bases. At least binary and octal.
		/// </remarks>
		public static double ToDouble(string value, System.Globalization.NumberStyles style, System.IFormatProvider provider)
		{
            if (value == null) return 0d;
			value = value.Trim();
			if (string.IsNullOrEmpty(value)) return 0d;

#if UNITY_WEBPLAYER
			Match m = Regex.Match(value, RX_ISHEX, RegexOptions.IgnoreCase);
#else
			Match m = Regex.Match(value, RX_ISHEX, RegexOptions.IgnoreCase | RegexOptions.Compiled);
#endif

			if (m.Success) {
				long lng = 0;
				style = (style  System.Globalization.NumberStyles.HexNumber) | System.Globalization.NumberStyles.AllowHexSpecifier;
				long.TryParse(m.Groups["num"].Value, style, provider, out lng);
				
				if (m.Groups["sign"].Value == "-")
					lng = -lng;
				
				return System.Convert.ToDouble(lng);
				
			} else {
				style = style  System.Globalization.NumberStyles.Any;
				double dbl = 0;
				double.TryParse(value, style, provider, out dbl);
				return dbl;
				
			}
		}
		
		public static double ToDouble(string value, System.Globalization.NumberStyles style)
		{
			return ToDouble(value, style, null);
		}
		
		public static double ToDouble(string value)
		{
			return ToDouble(value, System.Globalization.NumberStyles.Any, null);
		}
		
		public static float ToSingle(string value, System.Globalization.NumberStyles style)
		{
			return System.Convert.ToSingle(ToDouble(value, style));
		}
		public static float ToSingle(string value)
		{
			return System.Convert.ToSingle(ToDouble(value, System.Globalization.NumberStyles.Any));
		}

Hi there ! thanks you all for your help :slight_smile: !

I’ve tried Patico’s and mael5trom’s method but still got the error and float values where behaving weirdly. In fact, to put it in a context, I’m trying to Parse string values that come via OSC from VVVV (and many of them, coming in a list where I separate, assign and take them constantly with a foreach loop).

I noticed that the error only come one time, when I start the “game” and don’t come back after and everything works fine as VVVV keep sending fluctuating values, so maybe it’s just that at the start the Parse method try to parse a value before the OSC script is receiving the first ones, so there is no value at all during the first “frame” or something like this.

the values coming from VVVV are strings that look like this : x.xxxxx (ie 0.2564) so they are “clean” and unity do a good job with them, so I think I’ll keep my error for the moment xD.

thanks alot this solve my problem