In this specific example I would use Regular Expressions.
You can use RegEx to extract the value from the string as well as the unit so you can handle it accordingly.
The following should work: (\d+(?:\.\d+)?)\s?(\w?s)
The first capture group would provide the decimal part, and the second capture group would provide the unit (ns / ms / s). You can store the first capture group as a double and the second as a string and perform mathematical operations on the double based on the unit obtained. If it's ns then x10^-9, et cetera.
Alternatively, a more simple but less flexible solution would be to split the string based on spaces and then use the first value in the resultant array as a double and the second as a unit. This wouldn't work if you removed the space in the string, however. I prefer the RegEx solution as you know that if a match is found then the first capture group will contain a value and the second a unit.
If you're interested in the RegEx solution then I will break it down here:
(\d+(?:\.\d+)?)\s?(\w?s)
The (
indicates the start of a capturing group
The \d+
means that it is getting one or more decimal value
The (?:
indicates the start of a non-capturing group
The \.
means that it is looking for a dot
The )
indicates the end of a group (capturing or non-capturing)
The ?
means 'one or none of this'
The \s?
means one or more space
The \w?
means one or more letter
The s
means it is looking for an s
In summary, it is looking for a decimal value, followed by an optional space character, then any letter and an 's'. This means it would accept any of the following:
5.00ms
5.00 s
5.10 ns
5.1259 fs
241.015552ps
1 s
It would not accept:
12 wpwa
12a
pan
511.2012wprpwaroawroaroas
It would not accept the final one as the unit has to be two characters at most - one to designate how small, such as m or n, and another to state that it is in seconds (s).
If you were to decide that you would want any text after the number to show up in order to support text like "512.032 millis" then you can change the final (\w?s)
to (\w*s)
in the statement I provided.