简体   繁体   中英

How to reserve spaces in front of a double using printf() formatting in C

Consider the code, in the C programming language:

double d = 3.4;
printf("%02.2f", d);

or

double d = 3.4;
printf("%2.2f", d);

The output you get when running these blocks of code are:

3.40

I am trying to format a table and need to reserve spaces in front of a double or float so that my tables doesn't draw askew.

What is the best way to obtain the output

03.40

as intended?

double d = 3.4;
printf("%05.2f", d);

The width field is for the entire converted string (not just the whole number part).

03.40 does not seem to be a good solution. You should add either leading or trailing spaces, not zeroes.

The best option would be to use snprintf :

const size_t buffer_size = 16;

double value = 3.40;
char buffer[buffer_size];
int result = snprintf(buffer, buffer_size, "%.2f", value);

if(result > 0 && result < buffer_size)
    printf("Length of string: %d (%s)\n", result, buffer);

Output:

Length of string: 4 (3.40)

Try this code here: link .

Oh, one more thing: snprintf is a C++ 11 feature. If you doesn't have access to a C++11-compliant compiler, either use less safer version, sprintf , or use platform-specific solution like sprintf_s in case of Visual C++ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM