From 9d7ee5a5b9b6ca2093043b7c584df02913739b02 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Mon, 21 Mar 2011 22:03:55 +0000 Subject: floats can be output through the formatter again, except sometimes they're really ugly. --- src/formatter.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/formatter.h | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 97 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/formatter.cpp b/src/formatter.cpp index dcaa3a5..17fb311 100644 --- a/src/formatter.cpp +++ b/src/formatter.cpp @@ -10,6 +10,51 @@ #include "bu/stream.h" #include +template<> float Bu::tlog( float x ) +{ + return logf( x ); +} + +template<> double Bu::tlog( double x ) +{ + return log( x ); +} + +template<> long double Bu::tlog( long double x ) +{ + return logl( x ); +} + +template<> float Bu::tfloor( float x ) +{ + return floorf( x ); +} + +template<> double Bu::tfloor( double x ) +{ + return floor( x ); +} + +template<> long double Bu::tfloor( long double x ) +{ + return floorl( x ); +} + +template<> float Bu::tpow( float x, float y ) +{ + return powf( x, y ); +} + +template<> double Bu::tpow( double x, double y ) +{ + return pow( x, y ); +} + +template<> long double Bu::tpow( long double x, long double y ) +{ + return powl( x, y ); +} + Bu::Formatter::Formatter( Stream &rStream ) : rStream( rStream ), bTempFmt( false ), diff --git a/src/formatter.h b/src/formatter.h index f87a9be..a7689e1 100644 --- a/src/formatter.h +++ b/src/formatter.h @@ -11,10 +11,27 @@ #include "bu/string.h" #include "bu/fmt.h" +#include + namespace Bu { class Stream; + template t tlog( t x ); + template<> float tlog( float x ); + template<> double tlog( double x ); + template<> long double tlog( long double x ); + + template t tfloor( t x ); + template<> float tfloor( float x ); + template<> double tfloor( double x ); + template<> long double tfloor( long double x ); + + template t tpow( t x, t y ); + template<> float tpow( float x, float y ); + template<> double tpow( double x, double y ); + template<> long double tpow( long double x, long double y ); + class Formatter { public: @@ -118,8 +135,41 @@ namespace Bu void ffmt( type f ) { Bu::String fTmp; -// fTmp.format("%f", f ); -// writeAligned("**make floats work**"); + bool bNeg = false; + char cBase = fLast.bCaps?'A':'a'; + if( fLast.uRadix < 2 || fLast.uRadix > 36 ) + { + usedFormat(); + return; + } + + if( signbit(f) ) + { + bNeg = true; + f = -f; + } + int iScale = tfloor(tlog( f ) / tlog( (type)fLast.uRadix )); + f /= tpow( (type)fLast.uRadix, (type)iScale ); + + if( iScale < 0 ) + { + fTmp += "0."; + for( int j = 1; j < -iScale; j++ ) + fTmp += '0'; + } + int c = f; + fTmp += (char)((c<10)?('0'+c):(cBase+c-10)); + f -= (int)f; + for( int j = 0; j < 150 && f; j++ ) + { + if( iScale - j == 0 ) + fTmp += '.'; + f = f*fLast.uRadix; + int c = f; + fTmp += (char)((c<10)?('0'+c):(cBase+c-10)); + f -= (int)f; + } + writeAligned( fTmp ); usedFormat(); } -- cgit v1.2.3