I have an application that will need to perform a number of unit conversions (metric to Imperial, Imperial to metric).
Is there an existing Java library that does this? Or will I need to roll my own? (My initial Google searches proved moderately useless.)
there is a specific JSR 275 (javax.measure) with JScience as RI (Reference Implementation). For example converting 100 Miles to kilometers is easy as:
UnitConverter toKilometers = MILE.getConverterTo(KILOMETER); double km = toKilometers.convert(Measure.valueOf(100, MILE).doubleValue(MILE));
(note that units are all type safe a compile-time, a killer feature imho)
The reverse can be easy:
UnitConverter toMiles1 = KILOMETER.getConverterTo(MILE);
or supereasy as:
UnitConverter toMiles2 = toKilometers.inverse();
NB imports:
import javax.measure.Measure; import javax.measure.converter.UnitConverter; import javax.measure.quantity.Length; import static javax.measure.unit.NonSI.*; import static javax.measure.unit.SI.*;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With