Home > Software design >  Perl sprintf format number with leading zeros and 2 decimals
Perl sprintf format number with leading zeros and 2 decimals

Time:10-07

In Perl, I'd like to format a value with 2 leading zeros and two decimal places. e.g.

00.41

Using something like this doesn't work:

$dist = sprintf ("%2.2f", $dist);

What would be the correct format?

CodePudding user response:

Can force the whole string to have a certain width, and tell it to pad it with zeros. This would work since you want fixed (two) decimal places

my $str = sprintf ".2f", $num;

If the number ends up larger than this width (123.45, six places) you'll still see the whole number.

If the number indeed can be larger you can first work out the needed width, if you always want two extra leading zeros.


Or, since that's going to be a string anyway, just prepend a 0 once you format the number

my $str = '0' . sprintf "%.2f", $num;

or, really, just

my $str = sprintf "0%.2f", $num;

If two zeros need be added use '00'. That's about the only advantage of this over sprintf "%0${wd}.2f (where you work out the needed width $wd, or have it be a flat 5 if that's always it) -- that you can just slap as many zeros as you want.

Note that in all this the extra leading zero will go away if you do any numerics with it.

  • Related