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
Niklas Mertsch
  • 1,399
  • 12
  • 24
  • Possible duplicate of [Fixed digits after decimal with f-strings](https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings) – Marius Mucenicu Sep 25 '19 at 07:57
  • 1
    Why is `f'%.{precision}f' % a` a "horribly ugly solution"? – Aryerez Sep 25 '19 at 07: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... – Sam Mason Sep 25 '19 at 08:02
  • @Aryerez a) It mixes two string formatting concepts, b) as Sam said you perform two formatting operations. – Niklas Mertsch Sep 25 '19 at 08:03
  • @MariusMucenicu No, this is no duplicate, please at least read the questions' first sentence, not only the heading. – Niklas Mertsch Sep 25 '19 at 08:05
  • How is this **not** a duplicate? it's exactly that question, you just have to replace the precision with a variable...if the answer there says `f'{a:.2f}'`, you just had to replace `2` with a variable, literally like the answer you accepted. The question doesn't have to be `1:1` identical to be the same, it's the same context. – Marius Mucenicu Sep 25 '19 at 08:12
  • My question obviously shows two things: 1. I know that f-strings can be used for fixed precision (which is the whole content of your duplicate candidate), which means that your suggestion did not provide anything not included in the question. 2. I didn't know that nesting was possible in f-strings to provide precision and value in one pair of braces. The accepted answer adds that second part. – Niklas Mertsch Sep 25 '19 at 08:17

1 Answers1

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)
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • Thanks, didn't think it would be possible to do nesting in f-strings. – Niklas Mertsch Sep 25 '19 at 08:04
  • 1
    https://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 – Sam Mason Sep 25 '19 at 08:05