mirror of
https://github.com/transmission/transmission
synced 2024-12-24 08:43:27 +00:00
(trunk libT) #3521 "rounding issue in tr_truncd()" -- try yet again to work out all the fringe cases :)
This commit is contained in:
parent
1c2a7359af
commit
2ee5b08e94
2 changed files with 21 additions and 7 deletions
|
@ -1,3 +1,4 @@
|
|||
#include <math.h>
|
||||
#include <stdio.h> /* fprintf */
|
||||
#include <string.h> /* strcmp */
|
||||
|
||||
|
@ -379,6 +380,7 @@ static int
|
|||
test_truncd( void )
|
||||
{
|
||||
char buf[32];
|
||||
const double nan = sqrt( -1 );
|
||||
|
||||
tr_snprintf( buf, sizeof( buf ), "%.2f%%", 99.999 );
|
||||
check( !strcmp( buf, "100.00%" ) );
|
||||
|
@ -395,6 +397,15 @@ test_truncd( void )
|
|||
tr_snprintf( buf, sizeof( buf ), "%.2f", tr_truncd( 2.05, 2 ) );
|
||||
check( !strcmp( buf, "2.05" ) );
|
||||
|
||||
tr_snprintf( buf, sizeof( buf ), "%.2f", tr_truncd( 3.3333, 2 ) );
|
||||
check( !strcmp( buf, "3.33" ) );
|
||||
|
||||
tr_snprintf( buf, sizeof( buf ), "%.0f", tr_truncd( 3.3333, 0 ) );
|
||||
check( !strcmp( buf, "3" ) );
|
||||
|
||||
tr_snprintf( buf, sizeof( buf ), "%.2f", tr_truncd( nan, 2 ) );
|
||||
check( !strcmp( buf, "nan" ) );
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
|
@ -24,6 +24,8 @@
|
|||
#include <assert.h>
|
||||
#include <ctype.h> /* isalpha(), tolower() */
|
||||
#include <errno.h>
|
||||
#include <float.h> /* DBL_EPSILON */
|
||||
#include <locale.h> /* localeconv() */
|
||||
#include <math.h> /* pow(), fabs(), floor() */
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
@ -1431,14 +1433,15 @@ tr_parseNumberRange( const char * str_in, int len, int * setmeCount )
|
|||
***/
|
||||
|
||||
double
|
||||
tr_truncd( double x, int decimal_places )
|
||||
tr_truncd( double x, int precision )
|
||||
{
|
||||
/* sigh... surely there's a better way to do this */
|
||||
char buf[1024];
|
||||
const int i = (int) pow( 10, decimal_places );
|
||||
snprintf( buf, sizeof( buf ), "%f", x*i );
|
||||
*strchr(buf,'.') = '\0';
|
||||
return atof(buf) / i;
|
||||
char * pt;
|
||||
char buf[128];
|
||||
const int max_precision = (int) log10( 1.0 / DBL_EPSILON ) - 1;
|
||||
tr_snprintf( buf, sizeof( buf ), "%.*f", max_precision, x );
|
||||
if(( pt = strstr( buf, localeconv()->decimal_point )))
|
||||
pt[precision ? precision+1 : 0] = '\0';
|
||||
return atof(buf);
|
||||
}
|
||||
|
||||
char*
|
||||
|
|
Loading…
Reference in a new issue