1

I'm using jscience to parse some units for me:

    Unit<?> meter = Unit.valueOf("m");
    System.out.println(meter);

    Unit<?> foot = Unit.valueOf("ft");
    System.out.println(foot);

This prints out :

m
ft

I'd like it to print out

metre 
foot

Or something like this. In reality I'm actually reading in these unit strings, I have no control over what the user types, so I'd expect some to type "m", some to type "metre". When displaying it back, I'd like to always display it back as "Metre".

[Limitation]

The program is a large data storage program storing many different types of quantities. The user can store any quantity of any dimension (as long as it's defined in UCUM).

Andy
  • 3,228
  • 8
  • 40
  • 65

1 Answers1

4

You can use the UnitFormat class to specify how these classes get printed. Use the label method to specify the name, and the alias method to assist with parsing.

import java.io.IOException;

import javax.measure.unit.Unit;
import javax.measure.unit.UnitFormat;

public class ScienceUnit {

  public static void main(String[] args) throws IOException {
    Unit<?> meter = Unit.valueOf("m");

    StringBuilder sb = new StringBuilder();
    UnitFormat instance = UnitFormat.getInstance();

    instance.label(meter, "Metre");
    instance.format(meter, sb);

    System.out.println(sb.toString());
  }
}

Output:

Metre

Note that if you remove the instance.label line from this program, the output is:

m

The default value is the short form that you describe in your original post. I assume that the default values are the short form values described by UCUM, but I haven't actually checked.

durron597
  • 31,968
  • 17
  • 99
  • 158
  • Much appreciated. I've just been looking around in the decompiled jar and came to the same conclusion. Can I just confirm that I'm right in thinking that those labels aren't defined in the library anywhere? (Fine if they're not, it just saves me time if they are). – Andy Apr 16 '15 at 15:02
  • "I assume that the default values are the short form values described by UCUM, but I haven't actually checked." You should check. The source code seems to indicate that there is no UCUM implementation, and that the placeholder formatter is a default ASCII one that provides different values than those from UCUM. Plus JSR-275 has been superceded by JSR-363 (even though much of the codebase overlaps), and UCUM support has apparently been pulled from JSR-363 and its reference implementation. I can't find UCUM support anywhere. See http://stackoverflow.com/q/42653545/421049 . I appreciate any help. – Garret Wilson Mar 07 '17 at 17:07