• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 572
  • Last Modified:

string formatting using sprintf()


Can someone provide me with the correct formatting for display floating point values..

I know the following:

flat fvar=123;

sprintf(buffer,"%f ",fvar);   // this shows  123.000000
sprintf(buffer,"%.f",fvar);   // this shows  123
sprintf(buffer,"%.2f",fvar);   // this shows  123.00

what is the formatting to force zero padding

i.e

sprintf(buffer,"%05.2f",fvar); // to show  00123.00
sprintf(buffer,"%-5.2f",fvar); // to show  __123.00

thanks


0
apakian
Asked:
apakian
1 Solution
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi apakian,

Several things to note about the "%x.yf" format specification.  (x and y are replaced by numbers for actual usage.)

x is the TOTAL width of the output string, not the portion to the left of the decimal point.  If you want to display 5 digits to the left of the decimal and 2 to the right, x will need to be 8.  (5 + 2 + 1 for the decimal point.)

y is the number of digits to the right of the decimal point.

If x starts with a zero, the output string is initialized to all '0' and the converted string placed over these zeros.  The net effect is that you'll see leading zeros.

So to make your last two examples work like your comment, they should look like this:

sprintf(buffer,"%08.2f",fvar); // to show  00123.00
sprintf(buffer,"%-8.2f",fvar); // to show  __123.00



Good Luck,
Kent

0
 
apakianAuthor Commented:
brilliant,, thanks heaps..

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now