0

I have a program that adds doubles, but I want it to make it so that it displays the exact number without the zeroes. For example I added 13.4 and 10.05. It will show 23.450000. How do I make it so that it shows 23.45 without using %.2lf. I can't use %.2lf because if I add 12.4 and 10.1 it will show 22.50 but it needs to show 22.5 only. Sorry for the bad english.

  • "*that it shows*" be means of using what? `printf()`? – alk Mar 26 '16 at 08:57
  • `22.5` is not the same as `22.50` as `22.5` could for example also be `22.49` or `22.51` rounded. So showing `22.5` if you actually have `22.50` loses precision ("information"). So why show `22.5` if you have `22.50`? – alk Mar 26 '16 at 09:03
  • Why do you want to avoid the `%.2lf` format? – Peter Mar 26 '16 at 13:19

1 Answers1

0

What follows is not a full solution, but some hints on how you might want to proceed with your problem.

What you want is only achievable by first counting how many fractional digits your input numbers have - That decides how many fractional digits you need in the output. Obviously, that will only work if you have a string representation of your numbers.

/* necessary casts removed for clarity */
int fractionalDigs1 = arg1 + strlen(arg1) - strchr (arg1, '.') - 1;
int fractionalDigs2 = arg2 + strlen(arg2) - strchr (arg2, '.') - 1;

For addition of two numbers, you would want to have the output fractional digit count the maximum of the two input arguments' fractions, for multiplication the sum - you decide.

int fractionalDigsOut = max (fractionalDigs1, fractionalDigs2);

Output with a non-constant field width works with the field-width format specifier * like so (* takes an argument from the argument list and uses it as a field width):

printf ("%8.*f", fractionalDigitsOut, num);
tofro
  • 5,640
  • 14
  • 31