Schiavini Schiavini - 3 years ago 161
C# Question

Parsing measurement units

I have the following string:

string value = "123.456L";


What is the best way to parse this string into a string and a double:

double number = 123.456;
string measure = "L"


Instead of the L, we could also have something else, like
oz
,
m/s
,
liter
,
kilograms
, etc

Answer Source

Assuming that the units of measure are always expressed as a single character at the back of the string, you can do this:

string value = "123.456L";
var pos = value.LastIndexOfAny("0123456789".ToCharArray());
double number = double.Parse(value.Substring(0, pos+1));
string measure = value.Substring(pos+1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download