1

So I've looked around here a bit, but all the solutions that seem like they should work are not working for me. I have a string of text being entered into an input field. I want to convert that string to a float so that the user can enter a monetary value like "234.34".

I have already tried the following:

try
{
    float number = (float) Convert.ToDouble(_accountAmountInput.text);
}catch(Exception e)
{
    Debug.Log(e + "\n must be number");
}

AND

try
{
    float number = float.Parse(_accountAmountInput.text);
}catch(Exception e)
{
    Debug.Log(e + "\n must be number");
}

AND

if(float.TryParse(_accountAmountInput.text, NumberStyles.Any, CultureInfo.InstalledUICulture, out float number))
{
    Debug.Log("Number: " + number);
}
else
{
    //display error screen
    //account amount needs to be digits only
}

The last one outputs the correct number but I still get an error message I'm always entering a valid float value.

The error message I'm always getting is :

FormatException: Input string was not in a correct format. System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)

habib
  • 2,366
  • 5
  • 25
  • 41
cssg
  • 11
  • 1
  • Instead of `InstalledUICulture` use `InvariantCulture`. – Xiaoy312 Aug 16 '19 at 14:44
  • 1
    Some cultures use `,` as the fractional portion separator. Try to simplify the code until you get it to work. `float number = float.Parse("1.2");` or `float number = float.Parse("1,2");` – itsme86 Aug 16 '19 at 14:45
  • Possible duplicate of [Converting String To Float in C#](https://stackoverflow.com/questions/11202673/converting-string-to-float-in-c-sharp) – andyb952 Aug 16 '19 at 14:45
  • You may be using one of cultures like french where the decimal separator isnt `.`. You can confirm this by checking integer number works with your code. – Xiaoy312 Aug 16 '19 at 14:46
  • changing to InvariantCulture worked for me, Thanks! – cssg Aug 16 '19 at 14:48
  • And, don't "try-parse-catch" use "if-tryparse" instead. Exception handling is costly, don't use it unless you have no other option. – Xiaoy312 Aug 16 '19 at 14:49

1 Answers1

1

float is alias for Single, just use Convert.ToSingle

mobydi21
  • 11
  • 1