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

Hi monks, I just wondered if there was a way to reduce numbers such as 83.9774726111 to 3 significant figures?? If there is i'd love to know it! cheers

Replies are listed 'Best First'.
Re: reducing numbers
by broquaint (Abbot) on Apr 25, 2003 at 09:16 UTC
Re: reducing numbers
by elbow (Scribe) on Apr 25, 2003 at 09:20 UTC
    I'm assuming you want the number reduced to 83.977? If so, try sprintf.
    use strict; my $number = 83.9774726111 ; print sprintf("%.3f", $number); # produces 83.977

    But you should have been able to find this in any of the Camel books (Learning Perl, Perl Programming, etc).

    elbow
      Significant figures is not equivalent to the number of decimal places - This however is a fairly common mistake to make. The thread link provided by broquaint is quite informative as to the role and calculation of significant figures, in particular, this post from davis, which points to the Math::SigFigs module on CPAN.

       

      perl -le 'print+unpack("N",pack("B32","00000000000000000000001001010001"))'

      is it possible to use sprintf and print to a file; I have tried the following with no success;
      print OUTFILE sprintf("%.3f", $number);
      thanks

        Works ok for me, though you would be better off using printf.

        printf( OUTFILE "%3f\n", $number );