0

Is there a way to get the users input and then use that to decide what the precision of the outputted number should be?

What I mean is that I have a function to get the precision that the user wants and then I would want to be able to use that inputted number to decide how many decimal places should be shown. Normally when you are creating the program, you can decide it like this: printf("The number is: %0.2f", number);, but can that %0.2f also be dynamically changed so the user can decide if it should be 0.2, 0.3, 0.4, etc?

Daniel F.
  • 95
  • 8
  • 2
    It's straightforward to dynamically choose the *output* precision, with something like `prec = 5; printf("%.*f\n", prec, f);`. – Steve Summit Oct 17 '21 at 10:53
  • If you want to detect the precision of a floating-point number as the user types it, that's somewhat tricky, and there's no standard functionality do to it, so you have to do it yourself. See answers at [this recent question](https://stackoverflow.com/questions/69587724). – Steve Summit Oct 17 '21 at 11:16
  • Finally, be aware that once you've converted a user's input to a `float` or `double` variable, it's especially difficult (basically impossible) to discover how much precision the user originally entered it with, because internally these numbers are stored in *binary*. For example, if you enter 12.34 and store it in a `float`, the internal representation is a binary number equivalent to 12.340000152587890625, so you can't tell whether the user entered 12.34, or 12.3400001, or 12.34000015, or things like that. – Steve Summit Oct 17 '21 at 11:58

2 Answers2

3

can that %0.2f also be dynamically changed so the user can decide if it should be 0.2, 0.3, 0.4, etc?

Yes.

int prec = 2;
printf("The number is: %0.*f", prec, number);

Change prec to be what you want at runtime.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

Read the user’s input as characters. Test whether the user’s input is in an acceptable form. Count the number of digits the user entered. (You might count either the total number of digits or just the number after the decimal point, if any, as you choose.) Then convert the recorded characters to floating-point (e.g., use the strtod function).

When printing, using %.*f to fix the number of digits after the decimal point or %#.*g to fix the number of significant digits (total digits in the number from the first non-zero digit to the last non-zero digit). For either of these options, pass two arguments to printf: first the number of digits and second the number to be printed.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312