Sketchup ruby round number


#1

Hello,

I have a question about roundup or down a number.

i have the following formula:

o = hoh + hoh
b = depth
a = b/o

t = a
dp = 0 ### for 0 decimal places
t = (t10**dp).round10**-dp

What i want is the result form a =b/o, is roundup or down to a whole number. So if the result is, for example 5.43 is 5 and 6.79 is 7. But the code i found and used doesn’t seem to work.

Thanks for the help.


#2

Unless you need to support versions of SketchUp prior to SU 2014, you can just use the revised version of Float#round introduced in Ruby 1.9. It takes an argument specifying the number of decimal places to retain:

3.14159265.round(0) => 3
3.6.round(0) => 4

#3
5.44.round
=> 5
5.54.round
=> 6

In calculations you don’t normally need to worry.
Only if you are showing the result as a float in a UI.inputbox ?
If you are formatting as a text string you can use sprintf( )
Where you can do many clever things - e.g. always force 3 dps even when all 0 etc…
There are many examples here…
http://ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

Also remember that dividing integers can give different results from floats

3 / 2
=> 1
3 / 2.0
=> 1.5

#4

+1

For reference: http://ruby-doc.org/core-2.0.0/Float.html#method-i-round

Supplement the SketchUp API docs with the docs for Ruby itself to get a full overview of methods and classes available to you.


#5

Also, if you are dealing with model units then make sure to convert to Length and then rely on Length.to_s to convert the unit into the formatting of the current model.

http://www.sketchup.com/intl/en/developer/docs/ourdoc/length#to_s

For more information on dealing with units in SketchUp: http://www.thomthom.net/thoughts/2012/08/dealing-with-units-in-sketchup/


#6

Thanks to everyone it works!