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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With