Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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

In reply to Re: Dividing and format by davido
in thread Dividing and format by hotshot

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found