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

hi all this one seems to be easy but in my code
my $value = ($average)/($number);
I get a value of somthing like 2.2324342432 I need to only get three digits somthing like
$value = 2.24
thanks

Replies are listed 'Best First'.
Re: converting digits
by fuzzyping (Chaplain) on Jul 29, 2002 at 04:54 UTC
    Sprintf is your friend.

    -fp

    Update: Because I have a feeling about what you're going to ask next, I'll mention that printf is also your friend. Sprintf() returns the formatted string. Printf(), on the other hand, prints it to the currently selected filehandle (STDOUT by default).

    Update to my Update: Clarified any confusion regarding the use of sprintf and printf for BazB and Sara. The two functions are alternatives, not to be used at the same time. *sigh*

      Actually, if you're using sprintf to format text, you only need print to output the (formatted) text.
      If you want to format and output in one step, then you should use printf.

        I was simply clarifying the differences between the two functions. That's quite a leap of logic for you to infer that I was suggesting both should be used inclusively. Perhaps next time I'll keep my updates to myself. :-P

        -fp

        Update: BazB, sorry if that sounded confrontational. I just woke up, and didn't grok that I had to explain myself over something so elementary.
Re: converting digits
by monachus (Sexton) on Jul 29, 2002 at 05:38 UTC
    printf("%.2f",$value); will do exactly what you need
      Actually, no, sprintf is what she wants (as we've already mentioned), based on her question. She asked for a formatted value to be returned, not printed. Now see, you've made me go and waste more bits on this thread that were otherwise unnecessary.

      -fp