Skip to content

Commit

Permalink
First stab at supporting %f
Browse files Browse the repository at this point in the history
  • Loading branch information
lizmat committed Apr 11, 2019
1 parent 634c5de commit e6cbbcc
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion src/core/Rakudo/Internals/Sprintf.pm6
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,34 @@ class Rakudo::Internals::Sprintf {
make $value
}

# show floating point value
method directive:sym<f>($/ --> Nil) {

# handle precision / plus prefixing
my int $precision = $<precision> ?? +$<precision> !! 6;
my str $value = "pad-zeroes-rat($precision,"
~ value($/) # needs to be in outer scope
~ ".Numeric.round(10**-$precision).Str)";

# handle left/right justification / zero padding
if +$<size> -> $size {
if has_zero($/) {
$value = has_plus($/)
?? "prefix-plus(pad-zeroes-int($size - 1,$value))"
!! "pad-zeroes-int($size,$value)";
}
else {
$value = has_minus($/)
?? "str-left-justified($size,$value)"
!! has_plus($/)
?? "str-right-justified($size,prefix-plus($value))"
!! "str-right-justified($size,$value)";
}
}

make $value
}

# show numeric value in octal with Perl 6 roundtrippability
method directive:sym<o>($/ --> Nil) {
handle-integer-numeric($/, 8, "0o", False)
Expand Down Expand Up @@ -270,7 +298,7 @@ class Rakudo::Internals::Sprintf {

# show numeric value in octal
method directive:sym<x>($/ --> Nil) {
handle-integer-numeric($/, 16, "0x", ~$<sym> eq 'x')
handle-integer-numeric($/, 16, "0x", $<sym> eq 'x')
}
}

Expand Down Expand Up @@ -366,6 +394,21 @@ class Rakudo::Internals::Sprintf {
!! pad-zeroes-str($positions,$string)
}

# RUNTIME pad with zeroes after decimal point
sub pad-zeroes-rat(int $positions, Str:D $string --> Str:D) {
with $string.index(".") {
my int $digits = $string.chars - 1 - $_;
$positions > $digits
?? $string ~ " " x ($positions - $digits)
!! $string
}
else {
$positions
?? $string ~ "." ~ " " x $positions
!! $string
}
}

# RUNTIME pad with zeroes as string
sub pad-zeroes-str(int $positions, Str:D $string --> Str:D) {
my int $chars = $string.chars;
Expand Down

0 comments on commit e6cbbcc

Please sign in to comment.