From 03fff6e58dcff3e6027fca12a38390238b42a851 Mon Sep 17 00:00:00 2001 From: Marek Roszko Date: Tue, 13 Sep 2022 23:17:15 -0400 Subject: [PATCH] Use {fmt} for double -> string conversions Faster at printing floats than sprintf due to the modern algos --- common/base_units.cpp | 19 ++++++++++--------- common/string_utils.cpp | 27 +++++++++++++-------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/common/base_units.cpp b/common/base_units.cpp index 7ef28337bf..b7aa7ab3a7 100644 --- a/common/base_units.cpp +++ b/common/base_units.cpp @@ -35,6 +35,7 @@ */ #include +#include #include #include // for KiROUND #include @@ -213,24 +214,24 @@ wxString StringFromValue( EDA_UNITS aUnits, double aValue, bool aAddUnitSymbol, value_to_print = To_User_Unit( aUnits, value_to_print ); } - char buf[50]; + std::string buf; if( value_to_print != 0.0 && fabs( value_to_print ) <= 0.0001 ) { - int len = snprintf( buf, sizeof( buf ) - 1, "%.10f", value_to_print ); + buf = fmt::format( "{:.16f}", value_to_print ); - while( --len > 0 && buf[len] == '0' ) - buf[len] = '\0'; - - if( len >= 0 && ( buf[len]=='.' || buf[len]==',' ) ) - buf[len] = '\0'; + // remove trailing zeros + while( !buf.empty() && buf[buf.size() - 1] == '0' ) + { + buf.pop_back(); + } } else { - snprintf( buf, sizeof( buf ) - 1, "%.10g", value_to_print ); + buf = fmt::format( "{:.10g}", value_to_print ); } - wxString stringValue( buf, wxConvUTF8 ); + wxString stringValue( buf ); if( aAddUnitSymbol ) stringValue += EDA_UNIT_UTILS::GetAbbreviatedUnitsLabel( aUnits, aType ); diff --git a/common/string_utils.cpp b/common/string_utils.cpp index 1a4562f337..0cf9d4d184 100644 --- a/common/string_utils.cpp +++ b/common/string_utils.cpp @@ -31,6 +31,7 @@ #include #include // StrPrintf #include +#include /** @@ -1090,29 +1091,27 @@ void StripTrailingZeros( wxString& aStringValue, unsigned aTrailingZeroAllowed ) std::string Double2Str( double aValue ) { - char buf[50]; + std::string buf; int len; if( aValue != 0.0 && std::fabs( aValue ) <= 0.0001 ) { - // For these small values, %f works fine, - // and %g gives an exponent - len = sprintf( buf, "%.16f", aValue ); + // For these small values, 'f' works fine, + // and 'g' can result in exponent notation + buf = fmt::format( "{:.16f}", aValue ); - while( --len > 0 && buf[len] == '0' ) - buf[len] = '\0'; - - if( buf[len] == '.' ) - buf[len] = '\0'; - else - ++len; + // remove trailing zeros + while( !buf.empty() && buf[buf.size() - 1] == '0' ) + { + buf.pop_back(); + } } else { - // For these values, %g works fine, and sometimes %f + // For these values, 'g' works fine, and sometimes 'f' // gives a bad value (try aValue = 1.222222222222, with %.16f format!) - len = sprintf( buf, "%.10g", aValue ); + buf = fmt::format( "{:.10g}", aValue ); } - return std::string( buf, len ); + return buf; } \ No newline at end of file