M. Zim M. Zim - 3 years ago 109
C Question

print only decimal places of double

I want to print only the decimal places of a

double
with the
printf
statement in C. But not the first decimal places if they are 0. For example my doubles are

double number1 = 0.95;
double number2 = 0.05;


number 1
should be printed as
95
and
number 2
should be printed as
5
.

Answer Source

Something like this:

#include <stdio.h>
#include <string.h>

const char *trailingDecimals(char *buffer, size_t bufsize, double val)
{
    static const char *empty = "";
    snprintf(buffer, bufsize, "%.20f", val);
    char *result = strchr(buffer, '.');
    if (!result) return empty;
    while (*++result == '0');
    char *tail = buffer + strlen(buffer) - 1;
    if (*tail == '0')
    {
        while (*--tail == '0');
        *++tail = 0;
    }
    return result;
}

int main(void)
{
    double test = 12.00506;
    char buf[64];
    puts(trailingDecimals(buf, 64, test));
}

But be aware of precision issues, you might get more places than you expect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download