"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Does the Precision Field Actually Work with `%g` in `fmt.Printf`?

How Does the Precision Field Actually Work with `%g` in `fmt.Printf`?

Published on 2024-11-08
Browse:598

How Does the Precision Field Actually Work with `%g` in `fmt.Printf`?

Unexpected Behavior of fmt.Printf with Width and Precision Fields for %g

Understanding the Ambiguous Documentation

The documentation for fmt.Printf's formatting fields for floating-point values states that:

"For floating-point values, width sets the minimum width of the field
and precision sets the number of places after the decimal, if
appropriate, except that for %g/%G it sets the total number of digits."

The confusing part lies in the usage of "it" in the last sentence. It actually refers to "precision," not "width."

The True Behavior of %.9g

Contrary to the intuition that %.9g should produce a total of 9 significant digits, it actually only considers digits after the decimal point.

For example, 123456.789 will be formatted as 123.4e 03 because %.9g effectively truncates any leading zeros.

Conversely, 0.0000012345 will be formatted as 1.2345e-06 because %.9g considers all significant digits after the decimal point.

The Impact of width and precision

The width field specifies the minimum width of the entire formatted string, including the decimal point and exponent (if any).

The precision field, as described above, sets the number of significant digits after the decimal point.

For %g, the precision field overrides the width field. However, if the formatted string exceeds the specified width, it will extend beyond the specified width.

Explanation of the Given Example

Recall that the example involves formatting the following floating-point values using .9g:

  • 0.0606060606060606
  • 0.3333333333333333
  • 0.05
  • 0.4
  • 0.1818181818181818
  • 0.0606060606060606: The precision of 9 truncates the leading zeros, resulting in 0.0606060606, which fits within the width of 10.
  • 0.3333333333333333: Similar to the first example, the resulting string 0.333333333 fits within the width of 10.
  • 0.05: With only 2 significant digits, 0.05 is padded with spaces to meet the minimum width of 10.
  • 0.4: Similar to 0.05, 0.4 is also padded to meet the minimum width of 10.
  • 0.1818181818181818: The precision of 9 results in 0.181818182 with the trailing 2 being rounded up. This string fits within the width of 10.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3