6

I have a python program which takes some floating type values and writes to a file.

I round these numbers to 6 decimal places and then convert to a string type before writing to file.

file.write(str(round(value,6)))

However with certain numbers the value written to file is in the format shown below.

e.g. 3e-06 or 4e-03

How can I avoid this and instead write out in decimal format like

0.000003 and 0.004000

How can I print exactly 6 figures after the decimal point.

user94758
  • 97
  • 1
  • 1
  • 8
  • Perhaps this can help - https://stackoverflow.com/questions/2389846/python-decimals-format – Sanketh May 20 '19 at 08:36
  • 1
    @Sanketh Not exactly - `g` works differently from `f`. I included it in my answer for completeness. – gmds May 20 '19 at 08:39

2 Answers2

13

You can use the f-string f'{value:.6f}'.

Example:

value = 0.234
print(f'{value:.6f}')

value = 1
print(f'{value:.6f}')

value = 0.95269175
print(f'{value:.6f}')

Output:

0.234000
1.000000
0.952692

Also, in the answer linked in a comment, there was reference to :g. That can work, but probably not in this situation, because g may print scientific notation where appropriate, and discards insignificant zeroes. Consider a slightly modified example using g:

value = 0.234
print(f'{value:.6g}')

value = 1
print(f'{value:.6g}')

value = 0.000000000095269175
print(f'{value:.6g}')

Output:

0.234
1
9.52692e-11
gmds
  • 19,325
  • 4
  • 32
  • 58
0

You can also use basic string formatting:

a = 3e-06

# Outputs 0.000003
print('%.6f' % a)

# Outputs 0.000003000000
print('%.12f' % a)
Nasta
  • 819
  • 8
  • 21