Search code examples
pythonfloating-pointf-string

Prevent f string from converting float into scientific notation


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.


Solution

  • After checking other sources, I found numpy.format_float_positional which works very nicely here:

    import numpy as np
    number = 0.0000001
    string = f"Number: {np.format_float_positional(number)}"