<?xml version="1.0" encoding="windows-1252"?>
<node id="294424" title="Re: Display floating point numbers in compact, fixed-width format" created="2003-09-26 10:01:50" updated="2005-08-06 04:56:06">
<type id="11">
note</type>
<author id="85567">
particle</author>
<data>
<field name="doctext">
&lt;em&gt;&lt;blockquote&gt;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.&lt;/blockquote&gt;&lt;/em&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;i used your test suite, too.&lt;/p&gt;

&lt;code&gt;
#!/usr/bin/perl
use strict;
use warnings;
$|++;


Main();
exit;


## adapted from code found at: http://www.cs.tut.fi/~jkorpela/c/eng.html
sub eng
{
    my( $num, $digits )= @_;

    ## default to smallest number of digits allowing fixed width mantissa (4)
    $digits= defined $digits &amp;&amp; 3 &lt; $digits 
        ? $digits 
        : 4;
    
    my $neg;

    if( 0 &gt; $num )
    {
        $neg= 'true';
        $num= -$num;
    }

    0 == $num and return sprintf '+%.*fe+%s' =&gt; $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 &lt; $exp
        ? int( ( int( $exp / 3 ) ) * 3 )
        : int( int( ( -$exp + 3 ) / 3 ) * -3 );

    $num *= 10 ** -$exp;

    if( 1000 &lt;= $num )
    { 
        $num /= 1000;
        $exp += 3;
    }
    elsif( 100 &lt;= $num )
    {
        $digits -= 2;
    }
    elsif( 10 &lt;= $num )
    {
        $digits -= 1;
    }

    0 &lt;= $exp 
        and $exp= '+' . $exp;
    
    return ( $neg ? '-' : '+' ) 
        . sprintf '%.*fe%s' =&gt; $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;
        }
    }
}
&lt;/code&gt;

&lt;p&gt;~Particle *&lt;em&gt;accelerates&lt;/em&gt;*&lt;/p&gt;</field>
<field name="root_node">
293747</field>
<field name="parent_node">
293747</field>
</data>
</node>
