If I had a string "5/2", how could I use float.Parse to get 2.5? When I do it inside Unity3D I get an Invalid Format error. It works for whole numbers, like "5" would get 5, but I'm making a graphing calculator and a lot of times the slope of line is a fraction.
It is not a valid number, it is an expression which needs to be evaluated. you can do that using DataTable.Compute
. You can evaluate more complex expressions too using this technique.
var result = new DataTable().Compute("5/2",null);
Note: Datatable is expensive, so you can create a instance or static member which holds the reference of DataTable
for you.
Read more about compute in MSDN .
You'll need to split the string, parse the values individually and then do the division. So :
string[] tokens = input.Split('/');
float result = float.Parse(tokens[0])/float.Parse(tokens[1]);
Of course, you should add error handling to this, but that is "Proof of Concept" quality code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.