DEV Community 👩‍💻👨‍💻

Cover image for How to convert between any two units in Java using qudtlib
Florian Kleedorfer
Florian Kleedorfer

Posted on

How to convert between any two units in Java using qudtlib

We just released version 1.0 of a new project, qudtlib, which offers unit conversion and related functionality for over 1700 units, while being quite small: the jar-with-dependencies is ~400kB in size. The project is based on the QUDT ontology. Currently, this is available in Java only, but more is to follow.

For example

Let's say you want to convert feet into lightyears, here's what your java code would look like:

    Qudt.convert(
        new BigDecimal("1"),
        Qudt.Units.FT, 
        Qudt.Units.LY);
    --> 3.221738542107027933386435678630668E-17ly
Enter fullscreen mode Exit fullscreen mode

ok, now how do we know that's correct? Easy: we know that light travels about one foot per nanosecond, so if we multiply that number by the number of nanoseconds in a year, which is...

    Qudt.convert(
        new BigDecimal("1"),
        Qudt.Units.YR, 
        Qudt.Units.NanoSEC);
    --> 31557600000000000ns
Enter fullscreen mode Exit fullscreen mode

... we should get around 1. Let's try:

    Qudt.convert(
        new BigDecimal("1"),
        Qudt.Units.FT, 
        Qudt.Units.LY).getValue()
        .multiply(
            Qudt.convert(
                new BigDecimal("1"), 
                Qudt.Units.YR, 
                Qudt.Units.NanoSEC)
                   .getValue()));
    --> 1.01670336216396744710635782571955168476800000000000
Enter fullscreen mode Exit fullscreen mode

That's about 1. Seems to work ;-)

The Hack

The part of the QUDT ontology we need, including some additional data we generate, is about 3.5 MB in size. The libraries needed to access the data for providing the functionality we want have another 30+ MB. We felt that was too much for something as simple as converting celsius into fahrenheit (or feet to lightyears).

So we moved all the heavy lifting into the preprocessor (ie., maven) to generate a java class that instantiates all the objects representing the relevant part of the QUDT ontology upon startup. No SPARQL queries or other RDF munging at runtime, not a single external runtime dependency, You're welcome.

The big upside of this approach is that it should be relatively easy to port the solution to other languages.

What's on the Roadmap?

Typescript.

What else?

Well, you still don't know how many feet is a light year, so why don't you try qudtlib and find out?

Top comments (0)

🌚 Life is too short to browse without dark mode