Unit conversion in Java

JUGC is a Java library for unit conversions. It allows you to define a set of units and their relationships (a kilogram is a thousand grams, a tonne is a thousand kilograms, etc), translations for those units (gramma is fi_FI for gram), generate a Java library from those units (well, most of the library won't be generated, but the unit definitions will be) and then deploy that library in a project.

So basically you'll go from unit definitions like this:

    <units>
            <unit>
                    <id>fahrenheit</id>
                    <alias>F</alias>
                    <derive>celsius</derive>
                    <from>9 5 / * 32 +</from>
                    <to>32 - 9 5 / /</to>
            </unit>

            <unit>
                    <id>rankine</id>
                    <alias>R</alias>
                    <derive>fahrenheit</derive>
                    <from>459.67 +</from>
            </unit>
    </units>

to converting units like this:

    ConverterFactory.getConverter("celsius", "rankine").convert(42);

And the translation support is pretty simple, too:

    <units>
            <unit>
                    <id>gram</id>
                    <alias>g</alias>
            </unit>

            <unit>
                    <id>kilogram</id>
                    <alias>kg</alias>
                    <derive>gram</derive>
                    <from>1000 /</from>
            </unit>
    </units>

    <unittrans>
            <locale>fi_FI</locale>
            
            <translation>
                    <unit>gram</unit>
                    <trans>gramma</trans>
            </translation>

            <translation>
                    <unit>kilogram</unit>
                    <trans>kilogramma</trans>
            </translation>
    </unittrans>

And then in your code:

    ConverterFactory.getConverter("gramma", "kilogramma", "fi_FI").convert(42);

The conversion expressions are in RPN.

I have yet to make a release and it's not totally finished — it should be possible to ask for the conversions to be done with arbitrary precision math, for instance — but I believe it's pretty usable already.

License: BSD sans advertising clause.

© Juri Pakaste 2024