//
// Format a floating point value with number of decimal places.
// The 'precision' parameter is a number from 0 to 6 indicating the desired decimal places.
// The 'buf' parameter points to a buffer to receive the formatted string.  This must be
// sufficiently large to contain the resulting string.  The buffer's length may be
// optionally specified.  If it is given, the maximum length of the generated string
// will be one less than the specified value.
//
// example: fmtDouble(3.1415, 2, buf); // produces 3.14 (two decimal places)
//
void
fmtDouble(double val, byte precision, char *buf, unsigned bufLen)
{
    if (!buf || !bufLen)
        return;

    // limit the precision to the maximum allowed value
    const byte maxPrecision = 6;
    if (precision > maxPrecision)
        precision = maxPrecision;

    if (--bufLen > 0)
    {
        // check for a negative value
        if (val < 0.0)
        {
            val = -val;
            *buf = '-';
            bufLen--;
        }

        // compute the rounding factor and fractional multiplier
        double roundingFactor = 0.5;
        unsigned long mult = 1;
        for (byte i = 0; i < precision; i++)
        {
            roundingFactor /= 10.0;
            mult *= 10;
        }

        if (bufLen > 0)
        {
            // apply the rounding factor
            val += roundingFactor;

            // add the integral portion to the buffer
            unsigned len = fmtUnsigned((unsigned long)val, buf, bufLen);
            buf += len;
            bufLen -= len;
        }

        // handle the fractional portion
        if ((precision > 0) && (bufLen > 0))
        {
            *buf++ = '.';
            if (--bufLen > 0)
                buf += fmtUnsigned((unsigned long)((val - (unsigned long)val) * mult), buf, bufLen, precision);
        }
    }

    // null-terminate the string
    *buf = '\0';
}
コード例 #2
0
ファイル: DLSD.cpp プロジェクト: atiti/datalogger
void DLSD::pad_filename(char *filename, uint16_t c) {
	char nums[6];
	//itoa(c, nums, 10);
	fmtUnsigned(c, nums, 10);
	uint8_t a = strlen(nums);
	for(char i=0;i<a;i++) {
		filename[8-(a-i)] = nums[i];
	}	
}