in reply to Help with decimals

HyperZonk's way of doing it is much better, but if you didn't want to do "math" (and I'm really not sure why), you could use chop. It's much uglier, cumbersome and all around a worse method.. but in spirit of TIMTOWTDI..
#!/usr/bin/perl -w use strict; my $foo; $foo = 1500; print myformat($foo, 2) . "\n"; sub myformat { my ($number, $places) = @_; my $decimal; $decimal = ""; for (1 .. $places) { if ($number) { $decimal .= chop $number; } else { $decimal .= 0; } } return "$number\." . reverse $decimal; }
Update: Changed this to be a sub so it doesn't munge the original value as suggested by HyperZonk.

I also added the reverse because I no-so-brillantly forgot that the decimals would be reversed.

Rich

Replies are listed 'Best First'.
Re: Re: Help with decimals
by John M. Dlugosz (Monsignor) on Jul 30, 2001 at 03:09 UTC
    Your plucking the digits off one end, sticking on the dot, and sticking them back on sounds like something a regex should do!

    $number .= '0' while length($number) < $places; # add trailing zeros if needed $number =~ /(.{$places})/\.$1/;
    Or a substr
    # add trailing zeros, as above. substr ($number, -$places, 0, '.');
      Acutally a regex isn't all that good of an idea. It's very slow. But substr is better than chop.. benchmarks included..

      Benchmark: timing 100000 iterations of chop, math, regex, substr... chop: 6 wallclock secs ( 4.92 usr + 0.03 sys = 4.95 CPU) @ 202 +02.02/s (n=100000) math: 2 wallclock secs ( 1.07 usr + 0.02 sys = 1.09 CPU) @ 917 +43.12/s (n=100000) regex: 25 wallclock secs (17.40 usr + 0.32 sys = 17.72 CPU) @ 56 +43.34/s (n=100000) substr: 2 wallclock secs ( 1.99 usr + 0.03 sys = 2.02 CPU) @ 495 +04.95/s (n=100000)
      Doing the math is still the best option..