Use {fmt} for double -> string conversions

Faster at printing floats than sprintf due to the modern algos
This commit is contained in:
Marek Roszko 2022-09-13 23:17:15 -04:00
parent f304e2d4f6
commit 03fff6e58d
2 changed files with 23 additions and 23 deletions

View File

@ -35,6 +35,7 @@
*/
#include <base_units.h>
#include <fmt/format.h>
#include <string_utils.h>
#include <math/util.h> // for KiROUND
#include <macros.h>
@ -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 );

View File

@ -31,6 +31,7 @@
#include <macros.h>
#include <richio.h> // StrPrintf
#include <string_utils.h>
#include <fmt/core.h>
/**
@ -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;
}