简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM