0

I want to use a variable with an input value as the number of decimal places in C. The IDE that I'm using is CodeBlocks in Windows. Here's an example of the code that I tried to make (this is an example):

#include <stdio.h>
int main()
{
    int value;
    float number;
    printf("Enter a number (float).\n");
    scanf("%f", &number);
    printf("Enter a value.\n");
    scanf("%d", &value); 

    // here I'm trying to use the input value (float number) with the decimal places value (int value). 
    // In %.%df I'm trying to use the variable int value as the decimal places number
    // (example: %.2f, being 2 the decimal places number) even though it is an int variable.
    printf("The number %f with %d decimal places is %.%df.\n", 
        number, value, number, value); 

    return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
KazzioBots
  • 37
  • 5

1 Answers1

1

Use a * for the precision:

printf("The number %f with %d decimal places is %.*f.\n", number, value, value, number); 
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • .*: The precision is not specified in the format string, but as an additional integer value argument *preceding* the argument that has to be formatted. So `value` needs to go first. – yacc Apr 10 '20 at 23:19
  • 1
    Yup. I just copy/pasted OP's code without checking it. It worked for me in my quick test because of the behaviour of va_arg on my machine. Fixing! – Carl Norum Apr 10 '20 at 23:21
  • The `*` in `"%.*f"` is not the _width_. It is the _precision_. – chux - Reinstate Monica Apr 11 '20 at 04:34