We don't bite newbies here... much PerlMonks

### Re^2: sprintf percent formatting

by Roger (Parson)
 on Aug 17, 2005 at 12:59 UTC ( #484408=note: print w/replies, xml ) Need Help??

in reply to Re: 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:

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://484408]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2022-12-03 18:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?