After searching the archives I found the following routine from Bradly
Barton to convert float variables to string. Unfortunately it is not
working correctly: 6.964559 is converted to 6.10 (for round = 1). That'
s obviously wrong and there is also one digit more than there should be
(for round =1). It works correctly with values not so close to the next
full integer  (7 in this example, 6.55555 works OK) Can anybody fix
this? Is Bradly Barton still out there?

Thanks
Andreas.




void FloatToString (double value, char * buffer, int round)
{
// this function came from a combination of Thiago Rossato and
// Noah Young via the Palm Developer Forum
long iValue;
float dDecimal;
long iDecValue;
int i;
char sResult[50];
char sDecimal[50];

iValue = value;

dDecimal = value - iValue;

// if dDecimal >= 1, then iValue should actually be greater by dDecimal
// this happens in situations of numbers that can't be accurately
// represented as a double.. (7 is 6.9999999997, but dDecimal is 1 after

// the above)
if (dDecimal >= 1)
{
i = dDecimal;
iValue = iValue + i;
dDecimal = dDecimal - i;
}
// Make sure rounding will still work if value is negative
if (value < 0)
dDecimal = -dDecimal;

if (dDecimal < 0.000000001) dDecimal = 0;

if (!round && dDecimal >= 0.5) iValue++;

// Convert integer portion to string
StrIToA(sResult, iValue);
if (StrLen(sResult) < 1) StrCopy(sResult, "0");
if (round)
{
StrCat(sResult, ".");

// Round decimal portion
for (i = 1; i <= round; i++)
dDecimal = dDecimal * 10;

iDecValue = dDecimal;
if (dDecimal - iDecValue >= 0.5) iDecValue++;

// Add decimal portion
StrIToA (sDecimal, iDecValue);

// Add leading zeros if neccessary
if (StrLen (sDecimal) < round)
for (i = 1; i <= round - StrLen(sDecimal); i++)
StrCat (sResult, "0");
StrCat (sResult, sDecimal);
}

// Copy into return string
StrCopy (buffer, sResult);
}

----------
Bradly J. Barton - [EMAIL PROTECTED]
Jenies Technologies Incorporated
(972) 602-1835
http://www.JTI.net
http://HandAble.com



Andreas Zankl
University of Zurich
Switzerland


-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/support/forums/

Reply via email to