December 16, 2009

Yet Another Arduino Float Print Function

Note: in arduino-0017, floating point printing is supported by default. The function below is not necessary.

void floatPrint(float f, int places=6)
{
        int _d;
        if (f < 0)
        {
                Serial.print("-");
                f*=-1;
        }

        _d = (int)f;
        
        if (!places)
        {
                return;
        }

        Serial.print(_d, DEC);
        Serial.print('.');

        while(places--)
        {
                f-=_d;
                f*=10;
                _d = (int)f;
                Serial.print(_d, DEC);
        }
}

void floatPrintln(double f, int places=6)
{
        floatPrint(f, places);
        Serial.println();
}
Why another float print function? The ones I found wasn't too nice, one of which required long integers. Yuck. It was also fun, and now I know where to look for one in the future :P
Cheers,
Steve