Path: utzoo!attcan!uunet!cs.utexas.edu!samsung!munnari.oz.au!diemen!sol!quan From: quan@sol.surv.utas.oz (Stephen Quan) Newsgroups: comp.lang.c Subject: Re: **** a simple question **** Message-ID: Date: 17 Sep 90 08:18:45 GMT References: <793@babcock.cerc.wvu.wvnet.edu> Sender: news@diemen.utas.edu.au Lines: 38 siping@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@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@sol.surv.utas.edu.au) University of Tasmania, Aussie.