Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

by littleskittles (Initiate)
on Oct 01, 2014 at 05:30 UTC ( [id://1102512]=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 answer by Roy Johnson improved this answer by wrvhage by dealing with negative numbers. This answer adds an improvement to handle the case where decimal places is zero, i.e. by not including the hanging decimal point, e.g. "10.1" rounded to zero places would become "10." instead of "10". Any other changes are just rearrangement of the code.
sub stround { my ($n, $places) = @_; my $abs = abs $n; my $val = substr($abs + ('0.' . '0' x $places . '5'), 0, length(int($abs)) + (($places > 0) ? $places + 1 : 0) ); ($n < 0) ? "-" . $val : $val; }
  • 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://1102512]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-25 02:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found