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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.