1. As requested, a non-sprintf solution:
    $percent = int(100 * $one_thirtieth) . '%';
  2. Think about what rounding behavior you need; if $f = 888/1000, then:
    int(100*$f) will truncate to 88,
    sprintf(  '%d',100*$f) will truncate to 88,
    sprintf('%.0f',100*$f) will round to 89.
  3. You can merge formatting and concatenations into a single sprintf call:
    ok( $keyword_density >= $min_keyword_density, sprintf( 'Keyword density %.0f%%, minimum %.0f%%', 100 * $keyword_density, 100 * $min_keyword_density, ) );

Here is the code I was testing with:

use strict; use warnings; use Test::More; my @in_out = ( [ 1, 3 => '33%' ], [ 1, 30 => '3%' ], # [ 888, 1000 => '88%' ], # Use if we want truncation # [ -888, 1000 => '-88%' ], # Use if we want truncation [ 888, 1000 => '89%' ], # Use if we want rounding [ -888, 1000 => '-89%' ], # Use if we want rounding ); my @code = ( [ f1 => sub { int(100 * $_[0]) . '%' } ], [ f2 => sub { sprintf '%02d%%', 100 * $_[0] } ], [ f3 => sub { sprintf '%2d%%', 100 * $_[0] } ], [ f4 => sub { sprintf '%d%%', 100 * $_[0] } ], [ f5 => sub { sprintf '%.0f%%', 100 * $_[0] } ], ); plan tests => @in_out * @code; foreach (@code) { my ($name, $sub) = @$_; foreach (@in_out) { my ($numer, $denom, $expected) = @$_; my $frac = $numer / $denom; my $percent = $sub->($frac); is($percent, $expected, "$name($numer/$denom)"); # print "$name '$numer/$denom'\t'$expected'\t'$percent'\n"; } print "\n"; }


In reply to Re^4: sprintf percent formatting by Util
in thread sprintf percent formatting by tphyahoo

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.