HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonCritical

Fixed digits after decimal with f-strings

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fixeddigitsstringsafterdecimalwith

Problem

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)

For example, let's say I want to display 2 digits after the decimal place.

How do I do that? Let's say that

a = 10.1234

Solution

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Code Snippets

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Context

Stack Overflow Q#45310254, score: 1541

Revisions (0)

No revisions yet.