Elsa
Elsa

Reputation: 307

How do I format decimals in C?

This is my print statement:

printf("%d     %f\n",kPower, raisePower); 

This is my output:

-4     0.000100
-3     0.001000
-2     0.010000
-1     0.100000
0     1.000000
1     10.000000
2     100.000000
3     1000.000000
4     10000.000000

I want it to be printed like this:

enter image description here

UPDATE

So I made my positive values line up:

-4            0.0
-3            0.0
-2            0.0
-1            0.1
0            1.0
1           10.0
2          100.0
3         1000.0
4        10000.0

This is my new code so far:

printf("%d     %10.1f\n",kPower, raisePower);

I don't know, should I make a for loop to print each one (positive results vs negative result) in a different format?

Upvotes: 6

Views: 2797

Answers (7)

Havenard
Havenard

Reputation: 27934

#include <stdio.h>

char *get_number_formatted(double f)
{
    static char buf[128]; // this function is not thread-safe
    int i, j;

    i = snprintf(buf, 128, "%20.10f", f) - 2;

    for (j = i - 8; i > j; --i)
        if (buf[i] != '0')
            break;

    buf[i + 1] = '\0';
    return buf;
}

int main(void)
{
    int i;
    for (i = -4; i < 5; ++i)
        printf("%5d %s\n", i, get_number_formatted(pow(10.0, i)));
   return 0;
}

http://ideone.com/KBiSu0

Output:

   -4         0.0001
   -3         0.001
   -2         0.01
   -1         0.1
    0         1.0
    1        10.0
    2       100.0
    3      1000.0
    4     10000.0

printf() cannot print a variating length of decimal digits, so basically what I did was print the formatted number into a buffer and then cut the exceeding zeros.

Upvotes: 3

user3629249
user3629249

Reputation: 16540

use printf like this:

printf( "%5d %10.1f\n",kPower, raisePower);

this will result in kPower being printed, 
    right justified, 
    in 5 columns
    - sign in the right place

this will result in raisePower being printed with:
    10 columns
    leading 0s replaced by spaces
        except 1 digit (could be 0) to the left of the decimal point
    1 (rounded) digit to the right of the decimal point
    - signs being printed at the proper location
    decimal point being aligned

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41045

With a little help of modf, you can use %g to skip the trailing zeroes and \b to skip the leading zero:

#include <stdio.h>
#include <math.h>

int main(void)
{
    int i, iarr[] = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
    double darr[] = {0.0001, 0.001, 0.01, 0.1, 1., 10., 100., 1000., 10000.};
    double intpart, fractpart;

    for (i = 0; i < 9; i++) {
        fractpart = modf(darr[i], &intpart);
        if (fractpart == 0.0)
            printf("%10d%10d.0\n", iarr[i], (int)intpart);
        else
            printf("%10d%10d\b%g\n", iarr[i], (int)intpart, fractpart);
    }
    return 0;
}

Output:

    -4         0.0001
    -3         0.001
    -2         0.01
    -1         0.1
     0         1.0
     1        10.0
     2       100.0
     3      1000.0
     4     10000.0

Upvotes: 2

luser droog
luser droog

Reputation: 19514

You can use sprintf and then trim the zeros. This is the same idea as @Havenard's answer, but writing spaces over the zeros instead of cutting the string. And my C-style is somewhat different FWIW. My style is that I don't want to count or do any arithmetic in my head; that's what the C optimizer is for :).

#include <math.h>
#include <stdio.h>
#include <string.h>

int main() {
    int kPower;
    for(kPower=-4; kPower<5; kPower++){
        enum { bufsize = 2+5+10+1+4+1+1 };
        char buf[bufsize];
        int j,n,i;
        double raisePower = pow(10,kPower);
        //printf("%2d     %10.4f\n",kPower,raisePower);
        snprintf(buf,bufsize,"%2d     %10.4f\n",kPower,raisePower);
        j=strchr(buf,'.')-buf;
        j+=1;
        n=strchr(buf+j,'\n')-buf;
        for (i=n-1; i>j; i--)
            if (buf[i]=='0')
                buf[i]=' ';
            else
                break;
        printf("%s",buf);
    }   
    return 0;
}

Output:

-4         0.0001
-3         0.001 
-2         0.01  
-1         0.1   
 0         1.0   
 1        10.0   
 2       100.0   
 3      1000.0   
 4     10000.0   

Upvotes: 1

Eun
Eun

Reputation: 4178

Basicly you can use variable length to perform this:

printf("%d %.*lf", kPower, -kPower, raisePower);

Advantage over other methods is that this method does not need any extra buffer(s)

Upvotes: 2

Himanshu
Himanshu

Reputation: 4395

Try this example code

float y[7]={0.000100f,0.0010f,0.0100,0.1000f,1.0f,10.000f,100.00f};
int a[7]={-4,-3,-2,-1,0,1,2};
for(int i=0;i<7;i++)
    printf("%2d%20f\n",a[i],y[i]);

Output will like that.

enter image description here

Upvotes: 1

gyosifov
gyosifov

Reputation: 3223

Try calculating the powers first using pow() from math.h and then:

You can use %10f to precede the number with blanks in the example total of 10 spaces:

printf ("Preceding with blanks: %10f \n", 10000.01);

Source: cplusplus.com

Upvotes: 2

Related Questions