http://www.perlmonks.org?node_id=406653

replicant4 has asked for the wisdom of the Perl Monks concerning the following question:

mighty perl monks. I have the following print line.
printf "$l,$j,$Hx,$Hy,$Hxy,$mutual\n";
How can I use printf or sprintf in order to get only 3 decimal places for each of my $Hx, $Hy, $Hxy and $mutual values? Thanks in advance for your help

Replies are listed 'Best First'.
Re: use of print f and sprint f
by busunsl (Vicar) on Nov 10, 2004 at 12:16 UTC
    Have a look at the dokumentation of printf:

    perldoc -f sprintf

    You need a format string to format your values. You can try something like this:

    printf "$l, $j, %.3f, %.3f, %.3f, %.3f\n", $Hx, $Hy, $Hxy, $mutual;

      You should probably get into the habit of avoiding the interpolation of unchecked variables directly into the format string of (s)printf (as with $l and $j here) as a general rule - there has been some concern over the last few years about Format String vulnerabilities, and whilst it is not a flaw in Perl itself the underlying C libraries could potentially be vulnerable.

      /J\

        Hm, does this vulnerability really exist in perl? perldoc -f sprintf says perl uses its own formatting (just emulating libc's sprintf). The only exception are floating point numbers (with standard modifiers). I am not a security expert, but maybe someone who is (or someone who has digested the whole linked article) can tell if perl is really vulnerable here.
Re: use of print f and sprint f
by Happy-the-monk (Canon) on Nov 10, 2004 at 12:21 UTC

    ...printf or sprintf in order to get only 3 decimal places...

    According to perldoc -f sprintf, do it this way:

    printf "$l,$j,%.3f,%.3f,%.3f,%.3f\n", $Hx, $Hy, $Hxy, $mutual;

    Cheers, Sören