Scenario: Given a numeric value of cubic inches, … get a formatted string of volume in model units.
Note: Also discussing this at the SketchUp forums:
https://forums.sketchup.com/t/code-form ... nits/58562
VERSION 3
Adds "hideunit" boolean argument to handle the "SuppressUnitsDisplay" switch.
- Code: Select all
# format_volume_in_model_units( volume, spacing, precision )
#
# @param volume [Numeric] The volume in cubic inches.
# @param hideunit [Boolean] Whether to hide the unit symbols, or not.
# Defaults to the current model units "SuppressUnitsDisplay" switch.
# @param spacing [Integer] The spaces before unit symbol. (Default=0)
# @param precision [Integer] The numbers shown after decimal point.
# Defaults to the current model units precision (Range 0..6). Allows higher.
# @return [String] The volume in cubic model units.
def format_volume_in_model_units(
volume,
hideunit = Sketchup::active_model.options['UnitsOptions']['SuppressUnitsDisplay'],
spacing = 0,
precision = Sketchup::active_model.options['UnitsOptions']['LengthPrecision']
)
inch_side = Math::cbrt(volume)
unit_side = Sketchup::format_length(inch_side).to_f
unit_vol = unit_side**3
if hideunit
"%.#{precision}f" % unit_vol
else
i = Sketchup::active_model.options['UnitsOptions']['LengthUnit']
unit = ['in','ft','mm','cm','m'][i]
"%.#{precision}f%s%s³" % [ unit_vol, ' '*spacing, unit ]
end
end
VERSION 2
Barebones but might fail if the "SuppressUnitsDisplay" switch is true.
- Code: Select all
# format_volume_in_model_units( volume, spacing, precision )
#
# @param volume [Numeric] The volume in cubic inches.
# @param spacing [Integer] The spaces before unit symbol. (Default=0)
# @param precision [Integer] The numbers shown after decimal point.
# Defaults to the current model units precision (Range 0..6). Allows higher.
# @return [String] The volume in cubic model units.
def format_volume_in_model_units(
volume,
spacing = 0,
precision = Sketchup::active_model.options['UnitsOptions']['LengthPrecision']
)
inch_side = Math::cbrt(volume)
unit_side = Sketchup::format_length(inch_side).to_f
unit_vol = unit_side**3
unit = Sketchup::format_length(1.0).split(/~?\s*\d+\.?\d*/).last
unit = 'in' if unit == '"'
unit = 'ft' if unit == "'"
"%.#{precision}f%s%s³" % [ unit_vol, ' '*spacing, unit ]
end
(Note, Version 1, previously posted in another thread, was a “cutsie” one-liner that failed.)