Rounding
-
Hi everyone,
As you all know i'm knew to Sketchup ruby and i can't find this anywhere online.
I have a variable that has a float number and i wanted to round it.Var = 1.8854523497846
Desired answer Var = 1.9Also if i can recommend any online sources for Sketchup ruby Iβll be thankful
Thanks
-
Hi,
@unknownuser said:
Var = 1.8854523497846
Caution: this will create a constant (not very suitable for a variable)
var = 1.8854523497846
is better
a.floor # returns 1 a.ceil #returns 2 a.round #returns 2 a.round(1) #should return 1.9, but appears not to work as expected
SU uses Ruby 1.8.6 and .round(x) is new in Ruby 1.9. You'll have to wait for SU9 or code it yourself, or like this:
def prec(x) a=self.to_s.split(".") if not a[1] return self end if a[1].length > x-1 return(a[0] + "." + a[1][0..(x-1)]).to_f else dif=x-a[1].length return(a[0] + "." + a[1] + ("0"*dif)).to_f end end
var.prec(6) #returns 1.885452
See http://www.ruby-doc.org/core/ and select the 'Float' class.For online SketchUp-Ruby docs, see: http://forums.sketchucation.com/viewtopic.php?f=180&t=10142 (well done Dan !)
Hope this helps, -
@morci429: In reality.. there is no such think as "Sketchup Ruby." There is only Ruby, that that gets loaded by the Sketchup application, and then loads special Google API modules and classes, that extend Ruby so we can work with SKP models.
You need to learn Standard Ruby.. first. And you must have the Reference for the Standard Ruby Modules and Classes.
@didier bur said:
I suppose SU uses an older version of standard Ruby ?
See http://www.ruby-doc.org/core/ and select the 'Float' class.Yes, you poined to the current Ruby 1.9.x core.
I have links to the online 1.8.6 and 1.8.7 Core Refs, as well as downloadable offline CHM Refs in this post:
[url=http://forums.sketchucation.com/viewtopic.php?f=180&t=10142#p266725:1bdc3prs]RUBY PROGRAMMING REFERENCES[/url:1bdc3prs]
-
How about:
var = 1.8854523497846 var1 = ((var*10.0).round)/10.0
OR for a singleton Mixin method, save as 'mixin/float_round_to.rb'
(make a subfolder under plugins called 'mixin' and put the file there.):module Mixin; end module Mixin;;Round_to def round_to(num) places = 10.0**num return ((self.to_f*places).round)/places end end #module
then use it by extending your variable:
require('mixin/float_round_to.rb') var.extend(Mixin::Round_to) var1 = var.round_to(1)
1.9
var3 = var.round_to(3)
1.885
var8=var.round_to(8)
1.88545235 -
Many thank everyone
Dan Rathbun you are a genies
-
If you want to round it as output [as astring] then you can use
var_string = sprintf("%.1f", var)
for 1 dp etc
Advertisement