0

I want to convert a float like a = 1.1234567 to a string, giving the precision as a second variable (which is why this is no duplicate of "Fixed digits after decimal with f-strings"):

def float2str(val, precision):
    ...

float2str(1.1234567, 3)  # '1.123'
float2str(1.1234567, 5)  # '1.12346' (mind correct rounding)

I know that f-strings can do the correct rounding using f'{a:.5f}', but the precision has to be part of the string.

I came up with this horribly ugly solutions and hope someone can point me to a more elegant way:

f'%.{precision}f' % a
7
  • Possible duplicate of Fixed digits after decimal with f-strings Commented Sep 25, 2019 at 7:57
  • 1
    Why is f'%.{precision}f' % a a "horribly ugly solution"? Commented Sep 25, 2019 at 7:58
  • @Aryerez you're doing two string operations in that case, one to convert the precision to a string, then another that parses the precision out of a string and uses it to format the float... Commented Sep 25, 2019 at 8:02
  • @Aryerez a) It mixes two string formatting concepts, b) as Sam said you perform two formatting operations. Commented Sep 25, 2019 at 8:03
  • @MariusMucenicu No, this is no duplicate, please at least read the questions' first sentence, not only the heading. Commented Sep 25, 2019 at 8:05

1 Answer 1

3

you have a couple of options, given:

a = 1.1234567
b = 3

we can use either:

  1. using format strings: f'{a:.{b}f}'
  2. using old-style percent formatting: '%.*f' % (b, a)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, didn't think it would be possible to do nesting in f-strings.
pyformat.info contains lots of useful recipes like this, especially if you know one variant it helps for searching so you can translate between idioms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.