Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format decimals in C?

Tags:

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?

like image 429
Elsa Avatar asked Apr 28 '15 06:04

Elsa


People also ask

What does .2f mean in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.

Can you use decimals in C?

You can use decimal data types to represent large numbers accurately, especially in business and commercial applications for financial calculations. You can pass decimal arguments in function calls and in define macros.

How do I print a decimal in printf?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.


2 Answers

#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.

like image 93
Havenard Avatar answered Sep 19 '22 22:09

Havenard


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

like image 24
gyosifov Avatar answered Sep 17 '22 22:09

gyosifov