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
In reply to Re: Dividing and format
by davido
in thread Dividing and format
by hotshot
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |