cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

The community will undergo maintenance on October 16th at 10:00 PM PDT and will be unavailable for up to one hour.

Anyone worked with the Units API?

avillanueva
22-Sapphire II

Anyone worked with the Units API?

I am working with IBAs with unit and am trying to figure out the Units
API. I have an IBA with length units. It looks like the value is stored
in meters (m) in the system. I would like to output in another unit like
inch or centimeters. I have this:



UnitValueDefaultView unitIBA=(UnitValueDefaultView)attValue;



I assume I need to create a new Unit instance and feed it "cm" or "in".
It should know how to convert the values. What are the method calls to
convert?

3 REPLIES 3
avillanueva
22-Sapphire II
(To:avillanueva)

I think I have it.
UnitValueDefaultView unitIBA=(UnitValueDefaultView)attValue;
double value = unitIBA.getValue();
UnitDefView unit = unitIBA.getUnitDefinition();
log.debug("Value is " + value);
log.debug("Unit:"+unit.getName()+"|"+unit.getDescription());
log.debug("Unit Def Display String|" + unit.getDefaultDisplayUnitString("m"));
try {
double d=unitIBA.toUnit().convert("cm");
log.debug("Value is now " + d + " cm.");
}
catch (IncompatibleUnitsException e) {
log.debug(e.getMessage());
}
catch (UnitFormatException f) {}
log.debug("Now IBA is " + iba + "|" + unitIBA.getLocalizedDisplayString());

Resulting log:
Value is 0.05
Unit:WIDTH|CISPart Width
Unit Def Display String|m
Value is now 5.0 cm.
Now IBA is WIDTH|5E-2 m

So, you need to catch the exceptions I've listed above. The convert method takes a valid units string and converts the value to the new units. It does not change the underlying value of the IBA which is stored as the base unit. In this case, it is meters. Now, I just need to play with precision and significant figures. Just as a note, I entered this IBA value as centimeters when I created it as a Part attribute.

Thanks for the post Antonio, I know sometime in the near future I will need to play a bit with the classification system via API's, and handling units is going to be one of the challenges.
avillanueva
22-Sapphire II
(To:avillanueva)

Better way:
Unit unit=unitIBA.toUnit();
double d=unit.convert("cm");
log.debug("Value is now " + d + " cm.");
log.debug(unit.convertToString("cm", 1));
log.debug(unit.convertToString("cm", 2));
log.debug(unit.convertToString("cm", 3));
log.debug(unit.convertToString("cm", 4));

Log output:
Got HEIGHT|0.041 m
Value is now 4.1 cm.
4.
4.1
4.10
4.100
...
Got LENGTH|0.0387 m
Value is now 3.8700000000000006 cm.
4.
3.9
3.87
3.870


Announcements


Top Tags