[英]How do I convert a string to a float?
所以我在這里環顧了一下,但是所有看起來應該有效的解決方案都不適用於我。 我在輸入字段中輸入了一串文本。 我想將該字符串轉換為浮點數,以便用戶可以輸入像“234.34”這樣的貨幣值。
我已經嘗試了以下方法:
try
{
float number = (float) Convert.ToDouble(_accountAmountInput.text);
}catch(Exception e)
{
Debug.Log(e + "\n must be number");
}
和
try
{
float number = float.Parse(_accountAmountInput.text);
}catch(Exception e)
{
Debug.Log(e + "\n must be number");
}
和
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
}
最后一個輸出正確的數字,但我仍然收到一條錯誤消息,我總是輸入一個有效的浮點值。
我總是收到的錯誤消息是:
FormatException: 輸入字符串的格式不正確。 System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
float
是Single
別名,只需使用Convert.ToSingle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.