As it so happens, blakem and myself were playing with some (obfuscated?) code to perform just this task (precision formatting) for an array of numbers in this thread here. The best I think that I was able to come up with was this:

sub a{$_=int$_[0]*10**$_[1];s;(.{$_[1]})$;\.$1;;return$_};

This subroutine, while not particularly robust, takes two arguments, the number to format and the formatting precision - For example, the following code formats to single decimal precision:

my @a = ("1.10", "2.22"); print STDOUT &a($_, 1) for @a; sub a{$_=int$_[0]*10**$_[1];s;(.{$_[1]})$;\.$1;;return$_};

 

Update: After running this code through the test-suite written by Albannach, I would probably modify my subroutine as follows to clean up the subroutine output so that a trailing '.' isn't left at the end of a number if there is no decimals to follow it and to add rounding:

sub a{$_=int$_[0]*10**$_[1]+.5;s;(.{$_[1]})$;\.$1;;chop if substr($_,- +1)eq'.';return$_};

And the result ...

value|precision sprintf Incognito Albannach jeffa r +ob_au '123.45678'|3: 123.457 123.456 123.456 123 12 +3.457 '12.4'|1: 12.4 12.4 12.4 12 + 12.4 ''|0: 0 + 0 '3.14'|5: 3.14000 3.14000 3.14000 00003.14 3. +14000 '1'|5: 1.00000 1.00000 1.00000 00001 1. +00000 '.5'|0: 0 + 1 '10'|5: 10.00000 10.00000 10.00000 00010 10. +00000 '12.45435'|0: 12 12 12 12 + 12 '100'|5: 100.00000 100.00000 100.00000 00100 100. +00000 '3.'|0: 3 3 3 3 + 3 '1000'|5: 1000.00000 1000.00000 1000.00000 01000 1000. +00000 '12.56'|0: 13 12 12 12 + 13

 

Ooohhh, Rob no beer function well without!


In reply to Re: Using Regular Expressions to Simulate sprintf() function - One Liner Challenge by rob_au
in thread Using Regular Expressions to Simulate sprintf() function - One Liner Challenge by Incognito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.