Round-function ???
-
hi,
after a research i could point out this function:@var = @var.round.to_f
this works for me, but it seems , that the skp-ruby cannot use
round (x)
is that right?
if so, is there another "simple" syntax for rounding to 2 after comma - position ( or any other, of course) ?
thanx stan
-
@artmusicstudio said:
hi,
after a research i could point out this function:> @var = @var.round.to_f >
this works for me, but it seems , that the skp-ruby cannot use
round (x)
is that right?
if so, is there another "simple" syntax for rounding to 2 after comma - position ( or any other, of course) ?
thanx stan
Not clear what you attempted, but round is an instance method of Float. That is, you can do flt.round, but not round(flt). This is straight Ruby, not an SU issue.
You could define your own round function, such as (straight out of the Pickaxe book)
def round(val) return floor(self+0.5) if self >0.0 return ceil(self-0.5) if self<0.0 return 0.0 end
To get a specific number of decimal places, you could multiply by 10.0**2 before rounding and divide afterward. Note, however, that this will suffer the usual floating point imprecision because not all decimal fractions have exact binary representations. If you need exact two-place results you would be better off using a fixed point class.
steve
-
@artmusicstudio said:
if so, is there another "simple" syntax for rounding to 2 after comma - position ( or any other, of course) ?
If you want a rounded float in return:
<span class="syntaxdefault">module Example<br /> def self</span><span class="syntaxkeyword">.</span><span class="syntaxdefault">round</span><span class="syntaxkeyword">(</span><span class="syntaxdefault">number</span><span class="syntaxkeyword">,</span><span class="syntaxdefault"> precision</span><span class="syntaxkeyword">)<br /></span><span class="syntaxdefault"> i </span><span class="syntaxkeyword">=</span><span class="syntaxdefault"> 10.0 </span><span class="syntaxkeyword">**</span><span class="syntaxdefault"> precision<br /> </span><span class="syntaxkeyword">(</span><span class="syntaxdefault">number </span><span class="syntaxkeyword">*</span><span class="syntaxdefault"> i</span><span class="syntaxkeyword">).</span><span class="syntaxdefault">round </span><span class="syntaxkeyword">/</span><span class="syntaxdefault"> i<br /> end<br />end</span>
` Example.round(12.3456, 2)
> 12.35`
If you are formatting a number into a string to the UI you can use sprintf:
` sprintf('%.2f', 12.3456)> "12.35"`
Advertisement