Main Content

Being sure to be positive in Perl

Archive - Originally posted on "The Horse's Mouth" - 2006-09-15 13:38:04 - Graham Ellis

Perl's printf and sprintf routines (and functions with similar names in C and PHP, and the Python % operator) all provide us with a reasonably flexible way of formatting floating point numbers, but they can't meet every eventuallity. At times, you'll need to use sprintf to do most of the work then adjust it with some other facility such as regular expressions.

Example ... if you want to add a "+" sign onto the front of a positive number ... a couple of quick regular expressions will do the trick. And if you want to avoid "-0.00" being reported for a tiny negative number, you can do another fix. Here's the code:

sub price_format {
my $result = sprintf "%6.2f",$_[0];
$result =~ s/\s(\d)|^(\d)/+/;
$result =~ s/\s[-+]0\.(0+)$/ 0./;
return $result;


Written, you'll note, as a named block of code - a "sub" - so that you can easily store it in a module, reuse it, not have to work out those expressions again.

Complete code (commented and with test program) here

Sample output - showing special formatting in the left had column, and regular sprintf format to the right:

-1.65 -1.65
-1.10 -1.10
-0.55 -0.55
0.00 -0.00
+0.55 0.55
+1.10 1.10
+1.65 1.65