Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use float.Parse to get decimal from string like "5/2"

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.

like image 629
Tre B Avatar asked Jan 22 '26 15:01

Tre B


2 Answers

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.

like image 161
Sriram Sakthivel Avatar answered Jan 24 '26 06:01

Sriram Sakthivel


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.

like image 32
evanmcdonnal Avatar answered Jan 24 '26 05:01

evanmcdonnal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!