Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

How to round and keep floating digits

by juo (Curate)
on Oct 09, 2002 at 21:03 UTC ( [id://204052]=perlquestion: print w/replies, xml ) Need Help??

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

Does anybody know how to perform roundings but at the same time convert integers to float using the rounding parameters. I have been using Math::Round for that purpose however it does not add zeroes. See example below.

#!/perl/bin -w use strict; use Math::Round; # Not standard with Perl delivered my @number = qw(3 3.555 3.222334 3.4 1 0); for my $float(@number) { $float = nearest(.001, $float); print "$float\n"; } __END__ Result of Math::Round 3 3.555 3.222 3.4 1 0 This is what I want to get 3.000 3.555 3.222 3.400 1.000 0.000

Replies are listed 'Best First'.
Re: How to round and keep floating digits
by Zaxo (Archbishop) on Oct 09, 2002 at 21:16 UTC

    You want printf or sprintf:

    my @number = qw(3 3.555 3.222334 3.4 1 0); for my $float(@number) { $float = nearest(.001, $float); printf "%.3f\n", $float; }

    After Compline,
    Zaxo

Re: How to round and keep floating digits
by BrowserUk (Patriarch) on Oct 09, 2002 at 21:18 UTC

    Use printf "%5.3f\n", $float;


    Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!
      the following worked with perl, no need to use bash printf ("\n \t Pass Percentage = %0.2f %\n",$float); -Prasad

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2026-01-24 12:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (126 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.