You can round
a number to wanted scale:
>>> 12.8471 .round(0.01)
12.85
12.8471 is rounded to the nearest multiple of 0.01; effectively, 2 decimal places.
You have a sequence of numbers, so map
is there:
>>> (1, * + 𝑒 ... *) .head(5)
(1 3.718281828459045 6.43656365691809 9.154845485377136 11.87312731383618)
>>> (1, * + 𝑒 ... *) .map(*.round(0.01)) .head(5)
(1 3.72 6.44 9.15 11.87)
So for, e.g., 2 decimal points, need 0.01 == 10 ** -2; then we can argumentize this to the function:
sub euler-ex($x, Int :$digits) of Seq {
my $seq := 1, { $x ** ++$ / [×] 1 .. ++$ } ... Inf;
$digits
?? $seq.map(*.round(10 ** -$digits))
!! $seq
}
>>> euler-ex(5).head(6)
(1 5 12.5 20.833333 26.041667 26.041667)
>>> euler-ex(5, :3digits).head(6)
(1 5 12.5 20.833 26.042 26.042)
If $digits
is supplied (and nonzero...), the sequence will be returned back with its computed values rounded to that many decimal places. Otherwise, as is.
Noting that round
gives back a numeric value (e.g., Rational above), and 12.3. round(0.01)
would give 12.3
not 12.30
, i.e., trailing zeros are not put. If that is wanted, .fmt
as the other answer (but in map
; or sprintf
) is possible (noting that they give strings).
fmt
method 2 years ago while I was learning and frequently using Raku but after a long pause I had completely forgot it. So, that answer has been a nice reminder too :) – Snowstorm