Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
mrzo Avatar asked Feb 26 '20 09:02

mrzo


2 Answers

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

like image 85
Tin Nguyen Avatar answered Oct 17 '22 22:10

Tin Nguyen


numpy.format_float_positional works very nicely here:

import numpy as np
number = 0.0000001
string = f"Number: {np.format_float_positional(number)}"
like image 1
mrzo Avatar answered Oct 17 '22 20:10

mrzo