Search code examples
cfloating-pointfloating-point-conversion

How %g rounds up floating point numbers?


While I'm using %g as format specifier in printf(), sometimes it rounds up upto 2 places after decimal point, sometimes upto 3 places , someimes upto 4 places...how it does so?

Actually where we should use %g instead of %f or %e for floating point numbers?


Solution

  • The %g format specifier does its rounding just like %f would do, but if %f would result in 4.234000, then %g will omit the trailing zeros and print 4.234.

    %g should be used when it makes the most sense in your output format that some numbers are printed as 12345.6, while a slightly bigger number would be printed as 1.235e04.