Are there any C# libraries out there that provide the same kind of functionality google does when you type in a query such as “13 miles 743 yards in meters” it will return “21 600 meters” (for example).
What I want to be able to do is give a function the string part 13 miles 743 yards and it spits back an int/double with the given distance in meters. It needs to be able to handle all unit input types (kilometers/meters/furlongs/miles/yards/…) but the output only has to be in meters.
It isn’t that hard to write my own, but it would be great to just have a tested library ready to go.
I couldn’t find any answer to this, so I built my own 🙂 The only real ‘magic’ here is the Regex expression to grab the groups of values/units out of the original string. From there it’s simple fraction/number parsing and then working out how many meters each unit represents. I have not tested this much at all, so please let me know if you find improvements or bugs (the code below should throw an exception when it can’t handle a situation).
It won’t handle stupid user input, but provided the format of each section is “[number] [unit]” I think it should work fine. There is not much you can assume if the input doesn’t conform (e.g.,
12/32/43or1.43.3.2.44as a value) anyway. I think it will handle extra fluff in the sentence too such as1 kilometer and 10 miles(will strip out theand). I haven’t added every unit possible, if you know of a complete list of units & there meter equivalent I would love to know about it.Here are a couple tests,
and here is my code:
Enjoy! I hope someone out there finds this useful. Please leave comments/suggestions.
EDIT: added a
,to the regex string to handle1,300 metersstyle format