From b4592c0465f18d031dc1aecc3b854fe4ed04f8e9 Mon Sep 17 00:00:00 2001 From: Zoffix Znet Date: Fri, 18 Nov 2016 13:43:05 +0000 Subject: [PATCH] Improve readability of Rational.Str code - Avoid single-letter variables - Do not reuse the same variable for different purposes Part of bug hunt for 0.9999999999999999999999.Str => "0.10" --- src/core/Rational.pm | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/core/Rational.pm b/src/core/Rational.pm index 08c1c7def9d..cb3e46cb8ca 100644 --- a/src/core/Rational.pm +++ b/src/core/Rational.pm @@ -70,27 +70,27 @@ my role Rational[::NuT, ::DeT] does Real { multi method Str(::?CLASS:D:) { if nqp::istype($!numerator,Int) { - my $s = $!numerator < 0 ?? '-' !! ''; - my $r = self.abs; - my $i = $r.floor; - $r -= $i; - $s ~= $i; - if $r { - $s ~= '.'; - my $want = $!denominator < 100_000 - ?? 6 - !! $!denominator.Str.chars + 1; - my $f = ''; - while $r and $f.chars < $want { - $r *= 10; - $i = $r.floor; - $f ~= $i; - $r -= $i; + my $whole = self.abs.floor; + my $fract = self.abs - $whole; + my $result = ($!numerator < 0 ?? '-' !! '') ~ $whole; + + if $fract { + my $precision = $!denominator < 100_000 + ?? 6 !! $!denominator.Str.chars + 1; + + my $fract-result = ''; + while $fract and $fract-result.chars < $precision { + $fract *= 10; + given $fract.floor { + $fract-result ~= $_; + $fract -= $_; + } } - $f++ if 2 * $r >= 1; - $s ~= $f; + $fract-result++ if 2*$fract >= 1; # round off fractional result + + $result ~= '.' ~ $fract-result; } - $s + $result } else { $!numerator.Str