0

I use locale.format() to separate numbers into commas, but that function doesn't get rid of scientific notation. I want a way to return a number separated into commas, with trailed zeros and no scientific notation.

Example of actual code: 1160250.1294254328 -> 1.16025e+06

Example of I want: 1160250.1294254328 -> 1,160,250.13

My code:

locale.setlocale(locale.LC_ALL, 'en_US.utf8')

x = 1160250.1294254328
x = round(x, 2)
x = locale.format("%g", x, grouping=True, monetary=True)
theknightD2
  • 321
  • 6
  • 17
FoxGames01
  • 67
  • 1
  • 7
  • `'{:,.2f}'.format(1160250.1294254328)` --> `'1,160,250.13'` [Format String Syntax](https://docs.python.org/3/library/string.html#format-string-syntax) – wwii Dec 20 '21 at 01:54

2 Answers2

1

I've seen the first time that locale package to me.

Taking this opportunity to study the locale package, I found out that this package is very related to string formatting operations.

%g is only for exponential floating-point formatting.

Therefore, for the format you want, it is better to use the format below.

import locale

locale.setlocale(locale.LC_ALL, 'en_us.utf-8')
x = 1160250.1294254328
x = locale.format("%.2f", x, grouping=True, monetary=True)

print(x)

If you are interested in the String formatting operator check out the link below.

https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html

paul kim
  • 111
  • 5
0

Try use f-strings:

x = 1160250.1294254328
x = round(x, 2)
print(f"{x:,}") # -> Output: 1,160,250.13
JammingThebBits
  • 732
  • 11
  • 31