У меня есть строка с отрицательным числом с плавающей запятой и точкой, и она выглядит так:
-1.0
И мне нужно преобразовать его в float, поэтому он должен быть:
-1.0f
Я пробовал это:
bool isNegative = false; //float in my string isnt a negative
string mystr = "-1.0"; //my string
float myfloat = 0.0f; //my float
if(mystr.Contains("-"))
{
isNegative = true;
mystr.Replace("-");
} //if my string is negative,set a bool to true,and remove - from string
if(isNegative==true)
{
myfloat = float.Parse(mystr) * -1.0
} //if bool is true(is says number in string is negative),parse string to float and make it negative
else
{
myfloat = float.Parse(mystr)
} //if bool is false(number in string isnt negative),just parse a number
Я думаю, что этот код работает, но он выдает System.FormatException
, поэтому я думаю, что получил это исключение, потому что код не может проанализировать строку с точкой (.
). Я получил исключение в методе float.Parse
.
Если хотите, я покажу полный код, где я получил ошибку, верхний код - это просто концепция моего реального кода, есть реальный код:
bool redNeg = false; //red number isnt negative
bool greenNeg = false; //blue number isnt negative
bool blueNeg = false; //green number isnt negative
string[] args = GetArgs.ExtractArguments(LineText); //get strings from "translate(0.0,0.0,-1.0);"
string red = args[0]; //string1,default is 0.0
string green = args[1]; //string2,default is 0.0
string blue = args[2]; //string3,default is -1.0
if (red.Contains("-"))
{
redNeg = true;
red.Replace("-", "");
} //if string1 is negative,set negative bool to true and remove - from string
if (green.Contains("-"))
{
greenNeg = true;
green.Replace("-", "");
} //if string2 is negative,set negative bool to true and remove - from string
if (blue.Contains("-"))
{
blueNeg = true;
blue.Replace("-", "");
} //if string3 is negative,set negative bool to true and remove - from string
float redd = 0.0f; //default float of string1
float greenn = 0.0f; //default float of string2
float bluee = 0.0f; //default float of string3
if (redNeg==true)
{
redd = float.Parse(red) * -1.0f;
} //if negative bool of string1 is true,set float to negative
else
{
redd = float.Parse(red);
} //if its not,parse it
if (greenNeg == true)
{
greenn = float.Parse(red) * -1.0f;
} //if negative bool of string2 is true,set float to negative
else
{
greenn = float.Parse(green);
} //if its not,parse it
if (blueNeg == true)
{
bluee = float.Parse(red) * -1.0f;
} //if negative bool of string3 is true,set float to negative
else
{
bluee = float.Parse(blue);
} //if its not,parse it
gl.Translate((float)redd, (float)greenn,(float) bluee); //render function,dont touch it
После некоторых комментариев я отредактировал свой код следующим образом:
var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
//LineText is "translate(0.0,0.0,-1.0);
string[] args = GetArgs.ExtractArguments(LineText); //get strings from "translate(0.0,0.0,-1.0);"
string red = args[0]; //string1,default is 0.0
string green = args[1]; //string2,default is 0.0
string blue = args[2]; //string3,default is -1.0
float redd = float.Parse(red,fmt); //default float of string1
float greenn = float.Parse(green, fmt); //default float of string2
float bluee = float.Parse(blue, fmt); //default float of string3
gl.Translate((float)redd, (float)greenn,(float) bluee); //render function,dont touch it
Но у меня все еще есть FormatException, но теперь я его включил
float bluee = float.Parse(blue, fmt); //default float of string3
Это строка с отрицательным числом.
f
? Это необходимо только при определении переменной с плавающей запятой, когда вы анализируете подразумеваемую строку. Кроме того, ваше форматирование ужасно - person maccettura   schedule 12.10.2018f
. - person Byte   schedule 12.10.2018float.Parse
вызывает указанное исключение? Какую из строк вы вставили? - person meowgoesthedog   schedule 12.10.2018else { redd = float.Parse(red);
выдает ошибку - person Byte   schedule 12.10.2018MessageBox.Show(redd);
- person Byte   schedule 12.10.2018float.Parse("-1.0")
будет работать и делать именно то, что вы от него ожидаете (т.е. анализировать строку и выводить число с плавающей запятой со значением -1). Если у вас возникли проблемы с float.Parse, вам нужно показать нам, какие именно входные данные вы передаете методу синтаксического анализа, который вызывает проблему, и тогда мы сможем помочь вам диагностировать проблему. Если вы не знаете, какое значение вы передаете в float.Parse, вам действительно нужно изучить, как использовать отладчик для поиска этой информации. - person Chris   schedule 12.10.2018float.Parse(" -1.0 ")
будет правильно анализировать, поэтому пробелы не должны быть проблемой. - person Chris   schedule 12.10.2018red
. Мой предыдущий комментарий остается верным,f
на 100% не нужен в вашем контексте. Плюсfloat.Parse()
без проблем обработает отрицательный знак. Вам необходимо предоставить минимальный воспроизводимый пример - person maccettura   schedule 12.10.2018f
, потому что метод gl.Translate принимает float только сf
. - person Byte   schedule 12.10.2018