0

I've been trying to to display decimal points to 2 decimal places for a multiplication operation:

if (operation == multiplication)
    {
        printf("\n\n            You have chosen to perform a multiplication operation\n\n");
        printf("Please enter two numbers seperated by a space (num1 * num2): ");
        scanf("%f %f", &number1, &number2);

        total = number1 * number2;

        printf("\n%f times %f is equal to: %f", number1, number2, total);
    }

so if I enter 0.5 & 30 I'll get 15 and not 15.000000 and if I enter 0.5 & 15 I'll get 7.50 and not 7.5000000.

I'm still quite new to programming in C and in general as well, so detailed explanations would really be great. Thanks.

2 Answers2

3

Use printf with precision specifier:

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

int main(void)
{
    double x = 10.0, y = 10.5, dummy;

    printf("%.*f\n", (modf(x, &dummy) == 0) ? 0 : 2, x);
    printf("%.*f\n", (modf(y, &dummy) == 0) ? 0 : 2, y);
    return 0;
}

Output:

10
10.50
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

Just specify the decimal places like this:

printf("\n%.2f times %.2f is equal to: %.2f", number1, number2, total); 
         //^^See here ^^                ^^

For more information about printf() see here: http://www.cplusplus.com/reference/cstdio/printf/

Rizier123
  • 58,877
  • 16
  • 101
  • 156