Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How do I print/round a number to a given number of decimal places?

by Roy Johnson (Monsignor)
on Nov 04, 2003 at 16:04 UTC ( [id://304457]=note: print w/replies, xml ) Need Help??


in reply to How do I print/round a number to a given number of decimal places?

This other answer, by wrvhage, has the great property of working correctly for values like 3.005 rounded to two places (where sprintf is not). However, it needs a couple of tweaks to work for negative numbers.

sub stround { my( $n, $places ) = @_; my $sign = ($n < 0) ? '-' : ''; my $abs = abs $n; $sign . substr( $abs + ( '0.' . '0' x $places . '5' ), 0, $places ++ length(int($abs)) + 1 ); }

  • Comment on Re: How do I print/round a number to a given number of decimal places?
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://304457]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-25 23:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found