in reply to Re^2: sprintf percent formatting
in thread sprintf percent formatting

No no, I was happy with all three answers about dropping the 0. In fact, it was a testing situation that led me to post this question, but I am okay with my current Test::More solution, which winds up along the lines of
......code..... ok($keyword_density >= $min_keyword_density,"Keyword density " . sprin +tf("%2d%%",$keyword_density*100) . ", minimum " . sprintf("%2d%%",$mi +n_keyword_density*100) );
This seems elegant enough for me, but as always I welcome suggestions.

Replies are listed 'Best First'.
Re^4: sprintf percent formatting
by Util (Priest) on Aug 17, 2005 at 14:44 UTC

    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: