Created
May 11, 2012 12:59
-
-
Save gerdr/2659460 to your computer and use it in GitHub Desktop.
Rat to Str
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
sub rat2str(Rat $rat is copy, :$base = 10) { | |
my @str; | |
if $rat < 0 { | |
@str.push('-'); | |
$rat = -$rat; | |
} | |
my ($num, $denom) = $rat.nude; | |
@str.push: ($num div $denom).base($base), '.'; | |
$num mod= $denom; | |
if $num == 0 { | |
@str.push('0'); | |
return @str.join; | |
} | |
my %seen; | |
loop { | |
%seen{$num} = +@str; | |
$num *= $base; | |
while $num < $denom { | |
$num *= $base; | |
@str.push('0'); | |
} | |
@str.push: ($num div $denom).base($base); | |
$num mod= $denom; | |
last if $num == 0; | |
if %seen.exists($num) { | |
@str.splice(%seen{$num}, 0, '('); | |
@str.push(')'); | |
last; | |
} | |
} | |
return @str.join; | |
} | |
say .nude.join('/') ~ ' = ' ~ rat2str $_ | |
for 42.0, 1/5, -4/3, 19/12, 1/97; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment