I wanted something closer to "Engineering notation".... I'd like to be able to make the width a parameter (instead of fixed at 9). Being able to go as low as 7 (or even 6) would be way cool.
this code should meet those requirements. at least, the mantissa width is fixed, the exponent width varies. it should be easy enough to modify this code to suit your needs, if you wish.
i used your test suite, too.
#!/usr/bin/perl
use strict;
use warnings;
$|++;
Main();
exit;
## adapted from code found at: http://www.cs.tut.fi/~jkorpela/c/eng.ht
+ml
sub eng
{
my( $num, $digits )= @_;
## default to smallest number of digits allowing fixed width manti
+ssa (4)
$digits= defined $digits && 3 < $digits
? $digits
: 4;
my $neg;
if( 0 > $num )
{
$neg= 'true';
$num= -$num;
}
0 == $num and return sprintf '+%.*fe+%s' => $digits - 1, $num, 0;
my $exp= 0 != $num
## perl's log() is natural log, convert to common log
? int( log($num) / log(10) )
## short-circuit: can't do log(0)
: 0;
## tricky integer casting ahead...
$exp= 0 < $exp
? int( ( int( $exp / 3 ) ) * 3 )
: int( int( ( -$exp + 3 ) / 3 ) * -3 );
$num *= 10 ** -$exp;
if( 1000 <= $num )
{
$num /= 1000;
$exp += 3;
}
elsif( 100 <= $num )
{
$digits -= 2;
}
elsif( 10 <= $num )
{
$digits -= 1;
}
0 <= $exp
and $exp= '+' . $exp;
return ( $neg ? '-' : '+' )
. sprintf '%.*fe%s' => $digits - 1, $num, $exp;
}
sub Main
{
my $digits= 2;
for my $exp ( -101..-98, -11, -10..11, 98..101 )
{
for my $sign ( '', '-' )
{
my $num= 0 + ( $sign . "5.555555555e" . $exp );
printf "%-20s (%s)\n", $num, eng( $num, $digits );
}
}
for my $exp ( -10..11 )
{
for my $sign ( '', '-' )
{
my $num= 0 + ( $sign . "1e" . $exp );
printf "%-20s (%s)\n", $num, eng( $num, $digits );
printf "%-20s (%s)\n", 0, eng( 0, $digits )
if 1 == $num;
}
}
}
~Particle *accelerates*
-
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.