**** a simple question ****
Stephen Quan
quan at sol.surv.utas.oz
Mon Sep 17 18:18:45 AEST 1990
siping at cathedral.cerc.wvu.wvnet.edu (Siping Liu) writes:
>How can I print out ONLY the significant digits of
>a float number? As you know, "%f" fills in zero's if
>the number does not have enough non-zero digits after
>the point.
>
>I'd like to have:
> for 3.12, print out 3.12;
> for 3.0, print out 3.0;
> for 3.12349, print out 3.1235; (4 digits at most after the point)
>siping at cerc.wvu.wvnet.edu
Well let's see now, try this, maybe not efficient but short!
printreal(num)
float num;
{
char tmp[20];
int i;
/* get the number in nearly the format required. It even rounds up! */
sprintf(tmp,"%1.4f",num);
/* eliminate trailing zeros. */
/* for loop 1 just finds the end of the list. */
/* for loop 2 works backwards from end, eliminating the zeros. */
for (i=0 ; tmp[i] ; i++);
for (i-- ; (i>0) && (tmp[i]=='0') && (tmp[i-1]!='.') ; i--) tmp[i] = '\0';
/* print the formatted number out. */
printf("%s",tmp);
}
Stephen Quan, (quan at sol.surv.utas.edu.au)
University of Tasmania,
Aussie.
More information about the Comp.lang.c
mailing list