Ignore:
Timestamp:
Jul 14, 2009, 8:09:46 PM (13 years ago)
Author:
charles
Message:

(trunk) #2271: rounding problem in printf()

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/libtransmission/utils.c

    r8737 r8808  
    1818#include <ctype.h> /* isalpha, tolower */
    1919#include <errno.h>
     20#include <math.h> /* pow */
    2021#include <stdarg.h>
    2122#include <stdio.h>
     
    13261327***/
    13271328
    1328 static void
    1329 printf_double_without_rounding( char * buf, int buflen, double d, int places )
    1330 {
    1331     char * pch;
    1332     char tmp[128];
    1333     int len;
    1334     tr_snprintf( tmp, sizeof( tmp ), "%'.64f", d );
    1335     pch = tmp;
    1336     while( isdigit( *pch ) ) ++pch; /* walk to the decimal point */
    1337     ++pch; /* walk over the decimal point */
    1338     pch += places;
    1339     len = MIN( buflen - 1, pch - tmp );
    1340     memcpy( buf, tmp, len );
    1341     buf[len] = '\0';
     1329double
     1330tr_truncd( double x, int decimal_places )
     1331{
     1332    const int i = (int) pow( 10, decimal_places );
     1333    double x2 = (int)(x*i);
     1334    return x2 / i;
    13421335}
    13431336
     
    13501343        tr_strlcpy( buf, infinity, buflen );
    13511344    else if( ratio < 10.0 )
    1352         printf_double_without_rounding( buf, buflen, ratio, 2 );
     1345        tr_snprintf( buf, buflen, "%.2f", tr_truncd( ratio, 2 ) );
    13531346    else if( ratio < 100.0 )
    1354         printf_double_without_rounding( buf, buflen, ratio, 1 );
     1347        tr_snprintf( buf, buflen, "%.1f", tr_truncd( ratio, 1 ) );
    13551348    else
    13561349        tr_snprintf( buf, buflen, "%'.0f", ratio );
Note: See TracChangeset for help on using the changeset viewer.