mrzo
mrzo

Reputation: 2135

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.

Upvotes: 10

Views: 4424

Answers (2)

mrzo
mrzo

Reputation: 2135

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)}"

Upvotes: 1

Tin Nguyen
Tin Nguyen

Reputation: 5330

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

Upvotes: 9

Related Questions