5

I'm writing an application that needs to handle a fixed number of decimal places for floating-point numbers, which is easy enough with the f presentation type.

>>> f'{1.1:.2f}'
'1.10'

I also need number separators to be locale-aware as if using the n presentation type but n uses the same logic that g does to handle precision, so I end up losing the trailing zero (I need this)

>>> f'{1.1:.2n}'
'1,1'

Even worse, "n" shifts to e and loses digits for larger values where f keeps behaving sanely:

>>> f'{1234.:.2n}'
'1,2e+03'
>>> f'{1234.:.2f}'
'1234.00'

Is it possible to handle numbers the way f does, but with locale awareness of n without having to write my own formatting function?

  • Are you specifically asking about [how to format currency](https://stackoverflow.com/a/320951/11659881)? – Kraigolas May 28 '21 at 17:39
  • 1
    Not specific to currency (I would be using Decimal for that). I need 25 decimal places but used 2 in my examples for clarity. – Javier Gostling May 28 '21 at 17:41
  • Does this answer your question? [How to format a floating number to fixed width in Python](https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – Woodford May 28 '21 at 17:43
  • Similar to that, but using locale awareness for thousands and decimal separators. Instead of getting 1234.0000 I need to get 1,234.0000 – Javier Gostling May 28 '21 at 17:47
  • Does this answer your question? [How can I locale-format a python Decimal and preserve its precision?](https://stackoverflow.com/questions/31910741/how-can-i-locale-format-a-python-decimal-and-preserve-its-precision) – zr0gravity7 May 28 '21 at 17:47
  • @zr0gravity7 that answer is close in that it gives me localization, but the decimal digits are going up and down. I'm looking for 1234.1 to show up as 1.234,10 including the trailing zeroes to complete the required decimal places, and also 1.234 to show as 1,23 truncating excess decimals. – Javier Gostling May 28 '21 at 17:57
  • i dont think there is a possibility to solve your problem without formatting the float to a string, and manipulate the string. – Aru May 28 '21 at 21:34

0 Answers0