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

Ok I searched for rounding numbers and came up with this node.. what I need is to take a number like 490.408163265306 and round it to maybe 2 decimal places. Should I just use a regexp? or is there a simpler way?

Replies are listed 'Best First'.
Re: Decimal rounding
by BazB (Priest) on Feb 07, 2003 at 21:22 UTC
    my $num = sprintf('%.2f', '490.408163265306');

    perldoc -f sprintf for all the dirty details.

    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

Re: Decimal rounding
by Coruscate (Sexton) on Feb 07, 2003 at 21:25 UTC

    How do I print/round a number to a given number of decimal places? is the question you were looking for. Check out sprintf for the juicy details :)

    print sprintf("%.1f", 490.408163265306), "\n"; # 1 decimals print sprintf("%.2f", 490.408163265306), "\n"; # 2 decimals print sprintf("%.3f", 490.408163265306), "\n"; # 3 decimals

    Update: Aw, got beat like usual.


    If the above content is missing any vital points or you feel that any of the information is misleading, incorrect or irrelevant, please feel free to downvote the post. At the same time, reply to this node or /msg me to tell me what is wrong with the post, so that I may update the node to the best of my ability. If you do not inform me as to why the post deserved a downvote, your vote does not have any significance and will be disregarded.

Re: Decimal rounding
by Mr. Muskrat (Canon) on Feb 07, 2003 at 21:22 UTC

    Did you read all the way through Rounding numbers output? The last reply mentions using sprintf.

    my $number = 490.408163265306; my $rounded = sprintf("%.2f", $number); print "Number $number is now $rounded\n";

Re: Decimal rounding
by tachyon (Chancellor) on Feb 08, 2003 at 12:00 UTC

    While sprintf works to may want to use Math::Round which will let you round up/down/floor/ceil

    use Math::Round; print nearest(0.01, 1.256); __DATA__ 1.26

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print