Search code examples
pythonfloating-pointformattinglocalenumber-formatting

Suppress scientific notation with locale.format()


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)

Solution

  • 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