5
>>> '{:0.10}'.format(1/3)
'0.3333333333'
>>> '{:0.10}'.format(100/3)
'33.33333333'

The first gives 10 digits after the decimal point, the second gives 8. Does "precision" mean total digits? How do I control significant digits after the decimal point only?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Andy Fawcett
  • 51
  • 1
  • 2

1 Answers1

6

You need to include the type f (for float) to control the number of digits after the decimal place:

>>> '{:.10f}'.format(100/3)
'33.3333333333'

Without specifying the type, Python falls back to the general number type and the number is rounded to the specified number of significant digits. From the documentation:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • If the precision were just specifying the max size of the string, we'd be seeing one less digit. The reason we're seeing 8 digits after the decimal point is because an unspecified presentation type for `float`s treats the precision value mostly the same as `g`, where it means digits before and after the decimal point. – user2357112 Dec 03 '15 at 16:52
  • Yes, thanks, I referred to the wrong part of the documentation there (now fixed). – Alex Riley Dec 03 '15 at 17:09
  • got it. Thanks for your help. – Andy Fawcett Dec 03 '15 at 17:36