Search code examples
javajscience

Java Unit conversion


I have a database table which stores the units name in full like liters, kilograms, milliliters, milligrams etc.. I need a library to recogonize these units and convert it to the unit I wish to. How do i do this ?

Code Logic:

I will read the unit "liters" from database and i wish to convert it to milli-liters so her the input is "20 liters" and output should be "20000 milli-liters"

I downloaded JScience library but i am not sure how to do this. please tel me how to use that or suggest any alternative. It would be better if you explain me with a code sample. Thanks!!


Solution

  • I'm not aware that JScience provides a facility for parsing strings like "20 liters" (that spelling makes me cringe...), so you'll probably have to handle that yourself, by tokenizing the string into quantities and units.

    Once you have that, you can use JScience to convert between units easily enough, although obviously converting from litres to milliltres is trivial. But in principle, it's something like:

    Measure<Integer, Volume> input = Measure.valueOf(20, NonSI.LITRE);
    Measure<Integer, Volume> output = input.to(SI.MILLI(NonSI.LITRE));
    
    System.out.println(output);