Menu

#4 bug in dtoa

open
nobody
None
5
2015-11-01
2013-05-23
Edwin Chen
No

The correct way should be:

char dtoa( char aBuf, double aD )
{
double tmpTrunc = trunc( aD );
int tmpTruncInt = (int)tmpTrunc;
char tmpRes = itoa( aBuf, tmpTruncInt );
tmpRes++ = '.';

 static const int    biggestPowerOfTen   = 1000000; // = pow( 10, LONG_DIGITS );

 double              tmpMantissa         = ( tmpTruncInt >= 0 ) ? aD - tmpTrunc : tmpTrunc - aD;

 return uitoa( tmpRes, (int)( biggestPowerOfTen * tmpMantissa) );

}

There is still a small issue with rounding but on the original code the decimal portion was not being decoded.

Related

Feature Requests: #4

Discussion

  • Nimrods

    Nimrods - 2015-10-15

    Hi. This actually does not solve the entire issue with the dtoa here. Assuming your number is 3.04, the tmpMantissa will be 0.04. So biggestPowerOfTen * tmpMantissa will be 40000, and the result will be "3.40000"

     
  • Remi Chateauneu

    Remi Chateauneu - 2015-10-15

    Hi Nimrods
    Thanks for your contribution.
    Do you want to contribute this fix yourself to this project ?
    Remi

     
  • Edwin Chen

    Edwin Chen - 2015-10-17

    That is an issue! The code needs to left zero pad. Sorry i haven't tested this code but it is starting point:

    char dtoa( char aBuf, double aD )
    {
    double tmpTrunc = trunc( aD );
    int tmpTruncInt = (int)tmpTrunc;
    char tmpRes = itoa( aBuf, tmpTruncInt );
    
    tmpRes++ = '.';
     static const int    biggestPowerOfTen   = 10000; // = pow( 10, LONG_DIGITS );
    
     double              tmpMantissa         = ( tmpTruncInt >= 0 ) ? aD - tmpTrunc : tmpTrunc - aD;
     unsigned int        decimal             = (unsigned int)( biggestPowerOfTen * tmpMantissa)';
    
     // Left-zero padding
     size_t              pad                 = 4u - ilog_10( decimal );
     memcpy( tmpRes, "0000", pad );
     tempRes += pad;
    
     return uitoa( tmpRes, decimal );
    }
    
     

    Last edit: Edwin Chen 2015-10-17
  • Nimrods

    Nimrods - 2015-11-01

    Thanks. I'll give it a try.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.