[Glass] 10.12345 round: 2 => 10.12 ?
Martin McClure
martin.mcclure at gemtalksystems.com
Fri Nov 15 09:04:53 PST 2013
On 11/15/2013 08:44 AM, Martin McClure wrote:
> On 11/15/2013 06:20 AM, Mariano Martinez Peck wrote:
>> Hi guys... mmmm In Pharo we have the message #round:. Here it is :
>>
>> Float >> round: numberOfWishedDecimal
>> "only leave a fixed amount of decimal"
>> "10.12345 round: 2 => 10.12"
>> | v |
>> v := 10 raisedTo: numberOfWishedDecimal.
>> ^ ((self * v) rounded / v) asFloat
>>
>>
>> I see in GemStone Float has #roundTo: but doesn't seem to answer the
>> same...
>>
>
> From memory, #roundTo: is defined by ANSI to round to the nearest
> multiple of the argument -- so nnn roundTo: 2 would round to the nearest
> even number.
>
> To round with two decimal places, you would use roundTo: 1/100.
>
Also note that 0.01 is not exactly representable as a float, so if you
do this calculation on floats, you'll be getting some error, a larger
error the larger your number is, since you'll be rounding to a multiple
of a number that is not *quite* 1/100. And the result will probably not,
by default, print to a nice abc.de result -- it might be something like
10.1199998724.
It may be better to convert the float to a ScaledDecimal with two
fractional digits -- this will round precisely, and print nicely.
Or just use Fractions or ScaledDecimals in the first place and avoid
floats altogether. Which is better depends on your application.
Regards,
-Martin
More information about the Glass
mailing list