1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
// double xs[] =
std::vector <double> xs =
{
3.14159265,
22.6,
-7.43,
174,
1.26,
0.8
};
void fixed_iomanip_method( std::size_t max_non_fractional_digits )
{
// This method assumes a maximum non-fractional width of 3, + 1 for '.', + 6 fractional places
std::cout << "\nfixed iomanip method: " << max_non_fractional_digits << " + 1 + 6\n";
for (auto x : xs)
{
std::cout << std::fixed << std::setw( max_non_fractional_digits + 7 ) << std::setprecision( 6 ) << x << "\n";
}
}
template <class ToString>
void variable_strings_method( const char* message, ToString&& to_string )
{
// This method will pad the left of the converted strings to align the decimal point, if any
// The shape of the decimal->string conversion depends on your conversion function.
std::cout << "\nvariable strings method " << message << "\n";
std::vector <std::pair <std::string, std::size_t> > sns;
std::size_t max_n = 0;
for (auto x : xs)
{
auto s = to_string( x );
auto n = (s.find('.') == s.npos) ? s.size() : s.find('.');
max_n = std::max( max_n, n );
sns.emplace_back( std::make_pair( s, n ) );
}
for (const auto& [s, n] : sns)
{
std::cout << std::string( max_n - n, ' ' ) << s << "\n";
}
}
std::string to_string_and_strip_trailing_zeros( double x )
{
auto s = std::to_string( x );
auto n = s.find_last_not_of( ".0" );
return s.substr( 0, n + 1 );
}
int main()
{
fixed_iomanip_method( 3 );
variable_strings_method( "(standard)", (std::string (*)( double ))std::to_string );
variable_strings_method( "(strip trailing zeros)", to_string_and_strip_trailing_zeros );
xs.emplace_back( 1234.5678 );
fixed_iomanip_method( 3 );
fixed_iomanip_method( 4 );
variable_strings_method( "(standard)", (std::string (*)( double ))std::to_string );
variable_strings_method( "(strip trailing zeros)", to_string_and_strip_trailing_zeros );
}
|