0

Is there a simple, quick way in C to convert or print a float so that the output has a precision of two decimals (not more), but in case there are any trailing zeroes they get cut out?

Examples:

100.456 -> 100.46
100.32 -> 100.32
100.7046 -> 100.7
100.00 -> 100

Let's say we have float x; and we execute printf(%.2f, x). This would satisfy the first requirement, since any float would be printed with a maximum precision of 2 decimals. The problem though is that for x=100.00 or 100.7046 we would get respectively 100.00 and 100.70.

Using "g" as a format wouldn't fix the problem either. Any ideas?

Pensierinmusica
  • 6,404
  • 9
  • 40
  • 58

1 Answers1

-2

printf ("%.2f", 100.456); should give you 100.46

brbcoding
  • 13,378
  • 2
  • 37
  • 51
  • What about `100.7056 -> 100.7` and `100.00 -> 100`. –  Mar 05 '13 at 15:41
  • 1
    I thought you were looking to preserve trailing zeroes, not remove them... [This](http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c) is almost the exact same question and has several answers that might help you... – brbcoding Mar 05 '13 at 15:44
  • 1
    Thanks, but it doesn't answer the question. – Pensierinmusica Mar 05 '13 at 15:52