Force Python To Print A Certain Number Of Decimal Places
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 fi
Solution 1:
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
Solution 2:
You can also use basic string formatting:
a = 3e-06
# Outputs 0.000003
print('%.6f' % a)
# Outputs 0.000003000000
print('%.12f' % a)
Post a Comment for "Force Python To Print A Certain Number Of Decimal Places"