Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying floats using F-string

I'm really curious about why the behaviour is so different when add this "f" to the end of the number which I want to display:

# CASE with f
float1 = 10.1444786

print(f"{float1:.4f}")
# print out: 10.1445

# CASE without f
print(f"{float1:.4}")
# print out: 10.14

Why only 2 characters are displayed in the second example?

like image 425
Vesa95 Avatar asked Apr 13 '21 18:04

Vesa95


People also ask

What does F {} mean in Python?

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values.

What is the use of %F in Python?

Python string formatting It uses the % operator and classic string format specifies such as %s and %d . Since Python 3.0, the format function was introduced to provide advance formatting options. Python f-strings are available since Python 3.6. The string has the f prefix and uses {} to evaluate variables.

What is %d and %f in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.


1 Answers

The implied type specifier is g, as given in the documentation Thanks @Barmar for adding a comment with this info!

None: For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.

For Decimal, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.

The overall effect is to match the output of str() as altered by the other format modifiers.

An experiment:

for _ in range(10000):
    r = random.random() * random.randint(1, 10)
    assert f"{r:.6}" == f"{r:.6g}"

Works every time

From https://docs.python.org/3/library/string.html#formatstrings,

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1.

So in your second example, you ask for 4 sigfigs, but in your first you ask for 4 digits of precision.

like image 129
Pranav Hosangadi Avatar answered Oct 17 '22 11:10

Pranav Hosangadi