Solved

string formatting using sprintf()

Posted on 2004-09-30
2
541 Views
Last Modified: 2010-04-15

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
Comment
Question by:apakian
2 Comments
 
LVL 45

Accepted Solution

by:
Kdo earned 125 total points
ID: 12193411
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
 

Author Comment

by:apakian
ID: 12193463
brilliant,, thanks heaps..

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now