I was struck by this default behavior of f-strings in python 3.7.2:
>> number = 0.0000001
>> string = f"Number: {number}"
>> print(string)
Number: 1e-07
What I expected was: Number: 0.0000001
This is very annoying especially for creation of filenames. How can I disable this automatic conversion into the scientific notation? And why is it enabled in the first place?
Basically the opposite of this question.
Edit: I would like to avoid setting a fixed length for the float via {number:.8f}
since my numbers have different lengths and I don't want to have any trailing zeros. I want to use the f-strings to make filenames automatically, like this:
filename = f"number_{number:.10f}_other_number_{other_number:.10f}.json"
I am looking for a simple modifier that can disable the automatic scientific notation while keeping the original precision of the float.
https://docs.python.org/3.4/library/string.html#format-specification-mini-language
>>> number = 0.0000001
>>> f"Number: {number}"
'Number: 1e-07'
>>> f"Number: {number:f}"
'Number: 0.000000'
>>> f"Number: {number:.10f}"
'Number: 0.0000001000'
By default :f
has a precision of 6. You can change it to e.g. 10 with :.10f
numpy.format_float_positional works very nicely here:
import numpy as np
number = 0.0000001
string = f"Number: {np.format_float_positional(number)}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With