printf magic?

L

luser- -droog

I can't seem to figure out how to get printf to display a
real number with at least one fraction digit (even if it's
zero) but no unnecessary zeros. I've resorted to this:

void RScvs(state *st, object r, object s) { int n;
n = snprintf(STR(s), s.u.c.n+1, "%g", r.u.r);
if (strchr(STR(s), '.')==NULL) { strncat(STR(s),".0", s.u.c.n-n); n
+=2; }
if (n > s.u.c.n) error(st,rangecheck); if (n < s.u.c.n) s.u.c.n =
n; push(s); }

But I'm not really happy with it.

typedef struct composite {
address a;
size off;
size n;
} composite;

typedef struct object {
byte tag;
flags flags;
/* x86 puts two bytes of padding here
so the real (double) is 32-bit aligned
I don't know what to use it for.
*/
union {
boolean b;
integer i;
unsigned u;
real r; /* dominates the union */
composite c;
} u;
} object;
 
J

James Kuyper

I can't seem to figure out how to get printf to display a
real number with at least one fraction digit (even if it's
zero) but no unnecessary zeros. I've resorted to this:

Part of your specification mandates an unnecessary zero, and the other
part prohibits unnecessary zeros. You can make the specification
consistent by saying "no OTHER unnecessary zeros".

Would "%.1f"? Meet your needs? It won't use exponential notation, no
matter how large or small the number - but do you need exponential
notation? the combination of needing exponential notation and at least
one digit after the decimal point seems odd.
 
L

luser- -droog

Would "%.1f"? Meet your needs? It won't use exponential notation, no
matter how large or small the number - but do you need exponential
notation? the combination of needing exponential notation and at least
one digit after the decimal point seems odd.

But that limits the output to at MOST 1 decimal. %g appears to be the
only specifier that omits zero padding at the right; the problem is
it omits all of them and the period to if it can. But I need at least
one fraction digit so integers can be distinguished from reals in the
output. Oh, but I'd forgotten about exponential notation; that would
also distinguish them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top