howto get unit from string?

50 views
Skip to first unread message

Ryan McKinley

unread,
Nov 25, 2015, 1:54:17 PM11/25/15
to Units Users
Hello-

Is there a common way to get a Unit instance from a string?  For example given "km/h" I want:
 KILO(Units.METRE).divide(Units.HOUR).asType(Speed.class);

Thanks
ryan



Werner Keil

unread,
Dec 2, 2015, 6:43:19 AM12/2/15
to Units Users
Ryan,

Yes, there is. The main implementations of JSR 363 offer AbstractUnit.parse(String) as a convenience factory to the parse() method in UnitFormat implementations. 

demonstrates, the UCUM extension ([kph] follows its pattern, but does not overlap with any code defined by UCUM as of now) [kph] is properly parsed from a JSON string to Units.KILOMETRES_PER_HOUR, too.
Right now (and https://en.wikipedia.org/wiki/Kilometres_per_hour#Kilometres_per_hour_as_an_abbreviation shows, e.g. popular news agencies like Reuters until today use "kph") the US/Imperial "mph" was adopted to "kph", but given it seems the widest common practice by EU or SI now to use "km/h", I guess we'll adjust to that in all implementations where it's possible.

You should be able to call
SimpleUnitFormat.getInstance().label(Units.KILOMETRES_PER_HOUR, "km/h");
in your code and adjust the preferred label at any time (from the 0.8 GA version on) 
Note, some UnitFormat implementations that rely on properties or a similar storage may behave differently, but for SimpleUnitFormat (also used by AbstractUnit.parse()) it'll work.

I guess that answers your question. Let us know, if you need anything else.

Regards,
Werner
Reply all
Reply to author
Forward
0 new messages