Search code examples
perlscientific-notation

Getting perl to print in non scientific notation


I am running

./script.pl 69032 text.txt

Where text.txt contains

1   29  239 6

And I am getting

1   29  239 8.69162127708889e-05

As output but I just want the last number to be

1   29  239 .0000869162127708889

This is my script

$percent=$ARGV[0];
shift;
while(<>){
        my $temp = $_;
        my ($num, $start, $stop, $exp) = split("\t", $temp);
        if( defined($exp)){
                print $num,"\t",$start,"\t",$stop,"\t",$exp/$percent,"\n";
        }
}

Solution

  • Use printf for formatted printing. The details of format specifiers are given in sprintf.

    printf("%d\t%d\t%d\t%10.8f\n", $num, $start, $stop, $exp/$percent);
    

    The string inside "..." is where you specify how to format. The rest is a list of variables that are used in the string for each % specifier, in general in the order in which they come. The sprintf returns a string, while printf prints to STDOUT, or to another filehandle if given as the first argument, printf($fh "...", @vars). This is one of the most venerable, good old tools.

    Above we have: an integer %d, then a tab \t, then the same two times more, then a floating-point number to be printed in the field of total width 10 (including the decimal point and a possible sign) with 8 digits after the point. The integers take as much space in the output as they need -- one for 1, three for 239. If you want to line up the output you can specify the minimum width of the field

    printf("%3d\t%3d\t%3d\t%10.8f\n", $num, $start, $stop, $exp/$percent);
    

    Now each integer will take three spaces, aligned on the right. To align on the left use %-3d. To have leading zeroes you'd say %03d, for 001. Strings can be printed in fixed-width fields as well, so

    printf("%4s %6s %6s %12s\n", qw(num start stop factor));
    printf("%4d %6d %6d %12.8f\n", $num, $start, $stop, $exp/$percent);
    

    prints

     num  start   stop       factor
       1     29    239   0.00008692
    

    Above I chose field widths for a comfortable layout and used literal spaces as separators between them. (Tabs can mess with visual alignment if entries don't fit into tab stops. What has no effect on future parsing if this goes to a data file, even though they're no sugar for parsing either.) If you use commas instead that makes a CSV file.

    There is far, far more that one can do with this. It is used for anything from precise format conversions to printing data files or decent (ASCII) reports. The sprintf page is detailed with a lot of examples.