00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "stdafx.h"
00022
00023 #include "cfl/ToolStringPrefix.h"
00024
00025 #ifdef _DEBUG
00026 #define new DEBUG_NEW
00027 #undef THIS_FILE
00028 static char THIS_FILE[] = __FILE__;
00029 #endif
00030
00031 #ifndef dim
00032 #define dim(a) (sizeof(a)/sizeof(*(a)))
00033 #endif
00034
00035
00036
00037
00038
00039 CStringPrefix::CStringPrefix( double value, const char* format )
00040 {
00041 struct Table
00042 {
00043 double divisor; char* postfix;
00044 }
00045 table[] =
00046 {
00047 { 1e0 , "", },
00048 { 1e-3 , "m", },
00049 { 1e+3 , "k", },
00050 { 1e-6 , "u", },
00051 { 1e+6 , "M", },
00052 { 1e-9 , "n", },
00053 { 1e+9 , "G", },
00054 { 1e-12, "p", },
00055 { 1e+12, "T", },
00056 { 1e-15, "f", },
00057 { 1e+15, "P", },
00058 { 1e-18, "a", },
00059 { 1e+18, "E", },
00060 { 1e-21, "z", },
00061 { 1e+21, "Z", },
00062 { 1e-24, "y", },
00063 { 1e+24, "Y", },
00064 };
00065
00066 CString number;
00067 number.Format( format, value );
00068
00069 for ( Table* p = table; p < table + dim(table); ++p )
00070 {
00071 double x = value / p->divisor;
00072
00073 if ( 1 <= x && x < 1000 )
00074 {
00075 number.Format( format, x );
00076 number += p->postfix;
00077 break;
00078 }
00079 }
00080
00081 CString::operator=( number );
00082 }
00083
00084
00085
00086
00087
00088
00089
00090
00091 #ifdef BUILD_UNITTEST
00092
00093 #include <iostream>
00094
00095 typedef const char* charCptr;
00096
00097
00098
00099
00100
00101 int main()
00102 {
00103 double list[] =
00104 {
00105 1.23456e-66,
00106 1.23456e-16,
00107 1.23456e-15,
00108 1.23456e-14,
00109 1.23456e-13,
00110 1.23456e-12,
00111 1.23456e-11,
00112 1.23456e-10,
00113 1.23456e-9,
00114 1.23456e-8,
00115 1.23456e-7,
00116 1.23456e-6,
00117 1.23456e-5,
00118 1.23456e-4,
00119 1.23456e-3,
00120 1.23456e-2,
00121 1.23456e-1,
00122 1.23456e-0,
00123 1.23456e+1,
00124 1.23456e+2,
00125 1.23456e+3,
00126 1.23456e+4,
00127 1.23456e+5,
00128 1.23456e+6,
00129 1.23456e+7,
00130 1.23456e+8,
00131 1.23456e+9,
00132 1.23456e+10,
00133 1.23456e+11,
00134 1.23456e+13,
00135 1.23456e+14,
00136 1.23456e+15,
00137 1.23456e+16,
00138 1.23456e+66,
00139 };
00140
00141 for ( double* p = list; p < list + dim(list); ++p )
00142 {
00143 std::cout << *p << " : " << charCptr( CStringPrefix( *p, "%.3lg " ) ) << std::endl;
00144 }
00145
00146 return 0;
00147 }
00148
00149 #endif // BUILD_UNITTEST
00150
00151
00152
00153
00154