volume unit conversion

Need help, or want to share a macro? Post here!
User avatar
sliptonic
Posts: 1557
Joined: Tue Oct 25, 2011 10:46 pm

volume unit conversion

Postby sliptonic » Wed Jan 02, 2019 4:42 pm

I created a cube 100mm on a side so the volume should be 1 liter. The base unit for volume is microliter so

Code: Select all

>>> tu = FreeCAD.Units.parseQuantity
>>> tu(str(obj.Shape.Volume))
1e+06 
The closest I've gotten to expressing this in liters is:

Code: Select all

tu(str(obj.Shape.Volume) + 'µl')/tu('l')
1 1/mm^3
But that's pretty ugly.
I would think something like this would work but I get a unit mismatch error:

Code: Select all

Quantity(obj.Shape.Volume).getValueAs(FreeCAD.Units.Liter)
User avatar
sliptonic
Posts: 1557
Joined: Tue Oct 25, 2011 10:46 pm

Re: volume unit conversion

Postby sliptonic » Thu Jan 03, 2019 3:50 pm

Found my own solution:

Code: Select all

>>> vol = FreeCAD.Units.Quantity(obj.Shape.Volume,FreeCAD.Units.Volume)
>>> vol.getValueAs("l")
1 
User avatar
bernd
Posts: 8216
Joined: Sun Sep 08, 2013 8:07 pm
Location: Zürich, Switzerland

Re: volume unit conversion

Postby bernd » Sat Jan 05, 2019 6:17 am

:mrgreen: good one ...

I have done lots of Units code for FEM task panels, but for my own mass and volume calculations I had used hard coded Unit conversation, I do not why because this is way much smarter ...


Code: Select all

FreeCAD.open(FreeCAD.ConfigGet("AppHomePath") + 'data/examples/FemCalculixCantilever3D.FCStd')
myShape = App.ActiveDocument.Box.Shape

# not smart
myShape.Volume # in mm3
myShape.Volume * 1E-9 # in m3 not smart

# smart
vol = FreeCAD.Units.Quantity(myShape.Volume,FreeCAD.Units.Volume)
vol.getValueAs("l")
vol.getValueAs("m^3")
vol.getValueAs("mm^3")
User avatar
bernd
Posts: 8216
Joined: Sun Sep 08, 2013 8:07 pm
Location: Zürich, Switzerland

Re: volume unit conversion

Postby bernd » Wed Sep 11, 2019 12:02 pm

without FEM example ...

Code: Select all

myShape = Part.makeBox(8000,1000,1000)

# not smart
myShape.Volume # in mm3
myShape.Volume * 1E-9 # in m3 not smart

# smart
vol = FreeCAD.Units.Quantity(myShape.Volume,FreeCAD.Units.Volume)
vol.getValueAs("l")
vol.getValueAs("m^3")
vol.getValueAs("mm^3")