http://qs321.pair.com?node_id=484408


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

Well, I don't believe the OP wants to drop the leading 0. The OP wants to know if there is a more elegant way to write a test case without using sprintf. Correct me if I am wrong.

Replies are listed 'Best First'.
Re^3: sprintf percent formatting
by tphyahoo (Vicar) on Aug 17, 2005 at 13:14 UTC
    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.

      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: