def grow days
while days != 0
growheight = rand(5) / 100.0 @height = @height + growheight
days = days - 1
end
end
If days is a large number, say a year, it usually ends up with a number
like 7.4799999999999999984. Is there a way to fix this? Perhaps chopping
off after 2 decimal places in a string? Thanks in advance!
If days is a large number, say a year, it usually ends up with a number
like 7.4799999999999999984. Is there a way to fix this? Perhaps chopping
off after 2 decimal places in a string? Thanks in advance!
You might try using the % instance method of String.
For example:
"%.2f" % (1.0/3) => "0.33"
If days is a large number, say a year, it usually ends up with a number
like 7.4799999999999999984. Is there a way to fix this? Perhaps chopping
off after 2 decimal places in a string? Thanks in advance!
This is not as detailed but it may be worth a look.
n = 7.4799999999999999984
p n.round(2) #> 7.48
p n.round(1) #> 7.5
Apart from that it's not rounding. It's just a convenience way to
format a Float into a String. Really, usually you don't want to round
numbers but you want a specific output formatting.
Kind regards
robert
···
On Thu, Sep 15, 2011 at 4:47 PM, joe c. <joec54@gmail.com> wrote:
roger....that class is clever and it works great - thanks!
Also, rounding is rarely what one wants because it looses precision
and still gives no guarantee for proper output formatting. Usually
output formatting with printf, sprintf or % operator is better.
Btw, Joe if you are using floating point numbers for currency values
you might run into trouble soon because of the pecularities of IEEE
floating point math. In those cases it might be better to use
BigDecimal.