| 6 | namespace e57 |
| 7 | { |
| 8 | template <class FTYPE> std::string floatingPointToStr( FTYPE value, int precision ) |
| 9 | { |
| 10 | static_assert( std::is_floating_point<FTYPE>::value, "Floating point type required." ); |
| 11 | |
| 12 | std::stringstream ss; |
| 13 | ss.imbue( std::locale::classic() ); |
| 14 | |
| 15 | ss << std::scientific << std::setprecision( precision ) << value; |
| 16 | |
| 17 | // Try to remove trailing zeroes and decimal point |
| 18 | // e.g. 1.23456000000000000e+005 ==> 1.23456e+005 |
| 19 | // e.g. 2.00000000000000000e+005 ==> 2e+005 |
| 20 | |
| 21 | std::string s = ss.str(); |
| 22 | |
| 23 | // Split into mantissa and exponent |
| 24 | // e.g. 1.23456000000000000e+005 ==> "1.23456000000000000" + "e+005" |
| 25 | auto index = s.find_last_of( 'e' ); |
| 26 | assert( index != std::string::npos ); // should not be possible |
| 27 | |
| 28 | std::string mantissa = s.substr( 0, index ); |
| 29 | const std::string exponent = s.substr( index ); |
| 30 | |
| 31 | // Double check that we understand the formatting |
| 32 | if ( exponent[0] == 'e' ) |
| 33 | { |
| 34 | // Trim trailing zeros from mantissa |
| 35 | while ( mantissa.back() == '0' ) |
| 36 | { |
| 37 | mantissa.pop_back(); |
| 38 | } |
| 39 | |
| 40 | // Trim trailing decimal point if possible |
| 41 | if ( mantissa.back() == '.' ) |
| 42 | { |
| 43 | mantissa.pop_back(); |
| 44 | } |
| 45 | |
| 46 | // Reassemble whole floating point number |
| 47 | // Check if can drop exponent. |
| 48 | if ( ( exponent == "e+00" ) || ( exponent == "e+000" ) ) |
| 49 | { |
| 50 | s = mantissa; |
| 51 | } |
| 52 | else |
| 53 | { |
| 54 | s = mantissa + exponent; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | return s; |
| 59 | } |
| 60 | |
| 61 | template std::string floatingPointToStr<float>( float value, int precision ); |
| 62 | template std::string floatingPointToStr<double>( double value, int precision ); |