siping@cathedral.cerc.wvu.wvnet.edu (Siping Liu) (09/15/90)
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) How can I do this? Thanks for your help. siping@cerc.wvu.wvnet.edu
quan@sol.surv.utas.oz (Stephen Quan) (09/17/90)
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.
rick@tetrauk.UUCP (Rick Jones) (09/18/90)
In article <793@babcock.cerc.wvu.wvnet.edu> 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. Ever tried the "%g" format? e.g. printf ("%g", x); You can control the number of significant digits with e.g.: printf ("%.10g", x); note the parameter is significant digits, NOT decimal places IEEE doubles are not generally reliable beyond 15 sig. digits, so printf ("%.15g", x); will give you only significant digits, up to the maximum effective precision For very large or very small numbers, this format defaults to the equivalent of %e or %f respectively. For more info, read the manual! -- Rick Jones Nothing ever happens, nothing happens at all Tetra Ltd. The needle returns to the start of the song Maidenhead, Berks, UK And we all sing along like before rick@tetrauk.uucp - Del Amitri