How do I convert a number to unit of area?

I got a face’s area num : a = 136707.9693742, then I used Sketchup.format_area(a) got 88.2 m².
My question is, is there any method like to_m, to_mm that can directly conver the num 136707.9693742 to 88.2 without the .
Anyone would help me?

If you want to calculate the m2 of a Face that is not part of a group or component, you can calculate by dividing the face area by the factor to convert it to m2.

sel_face = Sketchup.active_model.selection[0]

factor_m2 = 1550
area_m2 = sel_face.area / factor_m2

puts area_m2

To use / test the above script, select 1 face in the model and then run this script with the Ruby Console.The output contains the m2 of the selected Face.

Thank you very much, you solved my problem!

More sophisticated and more general code snippet, just for fun…: :wink:
(Works in SketchUp 2020.0 or newer)
The result will depend what is in the current Model Info Unit settings and the regional settings
image

def area_text
  case Sketchup.active_model.options["UnitsOptions"]["AreaUnit"]
    when Length::SquareInches
      return " in²"
    when Length::SquareFeet
      return " ft²"
    when Length::SquareMillimeter
      return " mm²"
    when Length::SquareCentimeter
      return " cm²"
    when Length::SquareMeter
      return " m²"
    when Length::SquareYard
      return " yd²"
    else
      return ""
  end
end

def area_no_unit_str(number)
  Sketchup.format_area(number).sub(area_text, "")
end

def area_no_unit_float(number)
  dec_sep = Sketchup::RegionalSettings.decimal_separator
  area_no_unit_str(number).tr(dec_sep,".").to_f
end

puts area_no_unit_str(136707.9693742) #-> 88,199
puts area_no_unit_float(136707.9693742)  #-> 88.199

References:
Length

RegionalSettingsl#decimal_separator

Core-2.7.1/String.html

Yes (to specifically answer your question.)

Sketchup.format_area(a).to_f
#=> 88.2

… or …

a.to_m.to_m
#=> 88.19851352145888

To round …

a.to_m.to_m.round(1)
#=> 88.2

See what methods the API adds to the Numeric classes:

… in addition to the Ruby core base Numeric methods (such as #round )…

I am from a foreign country :slight_smile: , so this one for me returns:

#=> 88.0

I suggest:

  dec_sep = Sketchup::RegionalSettings.decimal_separator
  Sketchup.format_area(a).tr(dec_sep, ".").to_f
1 Like

… which is why I gave alternatives. :wink:

1 Like

Do you want the string (with no unit) or a float and do you want it to always be square meters or follow the model unit display settings? What do you want to use it for?

Often it’s good to stick to the internal SketchUp units as long as possible, and format only when printing the value to the user, but in such case there isn’t much reason to strip the unit.

That is what I want!
thank you very much!