routine round
1 | class Complex |
1.1 | (Complex) method round |
2 | role Real |
2.1 | (Real) method round |
3 | class Cool |
3.1 | (Cool) routine round |
Documentation for routine round
assembled from the following types:
class Complex
From Complex
(Complex) method round
Defined as:
multi method round(Complex: --> Complex)multi method round(Complex: Real() --> Complex)
With no arguments, rounds both the real and imaginary parts to the nearest integer and returns a new Complex
number. If $scale
is given, rounds both parts of the invocant to the nearest multiple of $scale
. Uses the same algorithm as Real.round on each part of the number.
say (1.2-3.8i).round; # OUTPUT: «1-4i»say (1.256-3.875i).round(0.1); # OUTPUT: «1.3-3.9i»
role Real
From Real
(Real) method round
method round(Real: = 1)
Rounds the number to scale $scale
. If $scale
is 1, rounds to an integer. If scale is 0.1
, rounds to one digit after the comma etc.
class Cool
From Cool
(Cool) routine round
Defined as:
multi sub round(Numeric(Cool))multi method round(Cool: = 1)
Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it to the unit of $unit
. If $unit
is 1, rounds to the nearest integer.
say 1.7.round; # OUTPUT: «2»say 1.07.round(0.1); # OUTPUT: «1.1»say 21.round(10); # OUTPUT: «20»
Always rounds up if the number is at mid-point:
say (−.5 ).round; # OUTPUT: «0»say ( .5 ).round; # OUTPUT: «1»say (−.55).round(.1); # OUTPUT: «-0.5»say ( .55).round(.1); # OUTPUT: «0.6»
Pay attention to types when using this method, as ending up with the wrong type may affect the precision you seek to achieve. For Real types, the type of the result is the type of the argument (Complex argument gets coerced to Real, ending up a Num). If rounding a Complex, the result is Complex as well, regardless of the type of the argument.
9930972392403501.round(1) .perl.say; # OUTPUT: «9930972392403501»9930972392403501.round(1e0) .perl.say; # OUTPUT: «9.9309723924035e+15»9930972392403501.round(1e0).Int.perl.say; # OUTPUT: «9930972392403500»