Created
May 9, 2012 19:44
-
-
Save TimToady/2648301 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
sub r2s (Rat $rat, $base = 10) { | |
my $s = $rat < 0 ?? '-' !! ''; | |
my $r = $rat.abs; | |
my $i = $r.floor; | |
$r -= $i; | |
$s ~= $i.base($base); | |
if $r { | |
my $want = $r.denominator < $base**6 ?? 6 !! $r.denominator.log($base).ceiling + 1; | |
my @f; | |
while $r and @f < $want { | |
$r *= $base; | |
$i = $r.floor; | |
push @f, $i; | |
$r -= $i; | |
} | |
if $r >= 0.5 { | |
for @f-1 ... 0 -> $x { | |
last if ++@f[$x] < $base; | |
@f[$x] = 0; | |
$s ~= ($i+1).base($base) if $x == 0; # never happens? | |
} | |
} | |
$s ~= '.'; | |
$s ~= [0..9,'A'..'Z'][@f].join; | |
} | |
$s; | |
} | |
say r2s(1/5000000000, 16); | |
say r2s(1/2000000000, 33); | |
say r2s(-(42+99999999999999/100000000000000), 2); | |
say r2s(:36<abigradixendswithz>/:36<10000000>, 36); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment