Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Dividing and format

by davido (Cardinal)
on Nov 27, 2003 at 17:42 UTC ( [id://310565]=note: print w/replies, xml ) Need Help??


in reply to Dividing and format

As others have mentioned, the obvious answer is to use sprintf as follows:

my $num = 12000/1000; my $string = sprintf "%.01f", $num; print $string, "\n";

But for no good reason I started thinking, hmm, what if we lived in some wierd world where sprintf didn't exist, but printf did?

One could write his own sprintf function by hand. But that's not nearly as fun as abusing Perl 5.8.0 (or later):

use strict; use warnings; require 5.8.0; my $num = 12; print format_str( "%.01f", $num ), "\n"; sub format_str { my $string; open STROUT, ">", \$string or die "You fool: $!\n"; printf STROUT shift, @_; close STROUT or die "trying: $!\n"; return $string; }

This method doesn't meet the OP's spec, because it uses printf. But I couldn't resist an opportunity to write to an in-memory file (held in a scalar, $string) and then turn around and use it as a plain old scalar later.

I dare you to turn that one in to the teacher. ;)

Update: Added 'require 5.8.0;' to my snippet to protect people who might otherwise ignore my suggestion that this is only a Perl 5.8.0 or later solution.


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-03-29 14:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found