electro103
electro103

Reputation: 147

How to write .5 in printf in C?

I want to print 0.5 value in ".5" form in ANSI C? I searched the web and stackoverflow, but I did not find what I want. I tried both "%.1f" and "%0.1f ". But neiter of them worked.

Upvotes: 1

Views: 715

Answers (3)

chux
chux

Reputation: 154228

After accept answer

Should code need to avoid troubles with large floating point values, INF, NaN or edge conditions like

printf(".%d", (int)(0.46*10)); // prints "0.4"

Post-process the string.

void PrintdNoLead0(double x) {
  const char *format = "%.1f\n";
  if (fabs(x) < 1.0) {
    char buf[10];  // Some buffer large enough for x in range -1<x<1
    sprintf(buf, format, x);
    char *p = strchr(&buf[1], '.');
    if (p[-1] == '0') {
      memmove(&p[-1], p, strlen(p));
    }
    fputs(buf, stdout);
  } else {
    printf(format, x);
  }
}

Upvotes: 1

Vladyslav
Vladyslav

Reputation: 786

There is no such specification in C to print fractional numbers without 0 at the begin. BTW you can use this code for your case:

printf(".%d", (int)(0.5*10));

Upvotes: 2

Igor Pejic
Igor Pejic

Reputation: 3698

Try this workaround:

double f = 0.5;

printf(".%u\n" , (unsigned)((f + 0.05) * 10));

Upvotes: 1

Related Questions