Search code examples
perlprintfprecision

Workarounds to print .00001 in perl


I have this program:

my $d = 40000 * 100 / 360;
print "At the equator\n";
printf "%9s° = %10.3f meters\n", 10**-$_, 10**-$_ * $d for 0 .. 7;

It outputs

At the equator (By the way, these are all off by a factor
of 10, but good thing that's not the point of the post.)
       1° =  11111.111 meters
     0.1° =   1111.111 meters
    0.01° =    111.111 meters
   0.001° =     11.111 meters
  0.0001° =      1.111 meters
   1e-05° =      0.111 meters
   1e-06° =      0.011 meters
   1e-07° =      0.001 meters

How can I fix my program so that exponential notation isn't used for the smaller numbers?


Solution

  • printf "%9.${_}f° = %9.3f meters\n", 10**-$_, 10**-$_ * $d for 0 .. 7;
    

    or

    printf "%9.*f° = %9.3f meters\n", $_, 10**-$_, 10**-$_ * $d for 0 .. 7;
    

    Output:

            1° = 11111.111 meters
          0.1° =  1111.111 meters
         0.01° =   111.111 meters
        0.001° =    11.111 meters
       0.0001° =     1.111 meters
      0.00001° =     0.111 meters
     0.000001° =     0.011 meters
    0.0000001° =     0.001 meters