I would like to convert a string to float in order to do math operations on it.
Here is my line of code where I want to convert the string, which is stored in an array to a float:
I have tried the following with no luck:
I have tried the following with no luck, and placed all my code.
//Here just reads text file and place everything in an array var regex : String = ","; var arr : Array = Regex.Split(downloadText,regex);
//Tested here, prints arr and arr fine
//Now just want to convert them into float so i can do some math var mensTotalTimes : float = float.TryParse(arr); var mensTotalTries : float = float.TryParse(arr);
//Printing mensAverageScore doesnt work var mensAverageScore : float = mensTotalTimes / mensTotalTries ;
/* THIS WORKS */ var mensTotalTimes : float = parseFloat(arr); var mensTotalTries : float = parseFloat(arr);
You want to use "float", not "Float". Aside from parseFloat(), there's also float.TryParse(), which can handle invalid input better.
answered Feb 16, 2010 at 03:40 AM
You should use float.Parse or float.TryParse (float is the same as Single). However, depending on your culture settings, floats can be represented with a comma (,) or dot (.) to separate the decimals.
If you want to use the following format "3.14" (as perhaps opposed to "3,14"), use the invariant culture number format System.Globalization.CultureInfo.InvariantCulture.NumberFormat.
See this post about number formats.
Also make sure to use the same culture info when converting floats back to strings since they will use your computers culture info by default (causing 3.14 to become "3,14"). Make sure to call ToString like this to get string "3.14".
answered Feb 16, 2010 at 09:50 AM
use float.parse to convert the string to float. also int and double and ... has a parse method too.
answered Feb 16, 2010 at 05:03 AM
private var myFloat : float; private var myString : String: private var anotherFloat : float;
myFloat = myString * anotherFloat;