I would like to round a floating points to various decimal places. What a pain in the neck. Here is what I did. I had tried many algorithms but they used arithmetic and produced bad results. I resorted to converting to a string. 2 questions:
- is there a better way to round a floating point number?
- I had used a %f in the sprint and it caused an invalid instruction trap. What's up with that?
double db_round(double value, int nDecimalPlaces)
{
char buf[16];
Uint16 u16Size;
/* find out number of digits to left of decimal. */
sprintf(buf, "%d", (Uint32)value);
u16Size = strlen(buf);
sprintf(buf, "%.*g", nDecimalPlaces+u16Size, value);
return atof(buf);
}