How to put a comma in Python 1000 units

Asked 2 years ago, Updated 2 years ago, 16 views

When I googled and tried to put a comma in every 1000 units,

number =  12345

number =  format(number, ',')

This and

import locale

locale.setlocale(locale.LC_ALL, '') 

n = -1234567890.123

s = locale.format('%.3f', n, 1)

What's the difference when there's this way?

python

2022-09-22 20:57

1 Answers

There are differences in the purpose of development, but the same results may be obtained depending on the use.

A format function is a function that formats a value. For example, binary, octal, decimal, hexadecimalA function that, when you make the width n, such as expressing it with an index or a percentage, specifies the format of filling in the empty space with 0 or a space, and makes it a string. (For dates

The format function can be written in the following ways:

format(value, "format rule") or
"{Formality Rules}".format (value)
print(format (1234, ",") # Every 3 digits, add
print (format (1234, "E") # expressed as an index
print (format (1234, "X") # expressed in hexadecimal
print(format(1234, "_>-012,.2f"))

In the last example above, fill in the empty space with _ (the first letter is the fill letter), match the number to the right (> character), mark only negative (-), and always output it to 12 digits (012), and add a decimal point ().2character) expressed as a decimal (fcharacter).

This is a function that you use to support multiple languages, and usually in numeric notation, especially when you use currency, there are different functions by country. It's a function that we use to express these things by country.

locale.format("Format rule", number, currency format)

In the example of the question, .3f is .3 means 3 decimal places and f means decimal places. For monetary, add , if true, or , if false, do not add .

Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.

If monetary is true, the conversion uses monetary thousands separator and grouping strings.

Please note that this function will only work for exactly one %char specifier. For whole format strings, use format_string().

Changed in version 2.5: Added the monetary parameter.

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

format(value, format_spec) merely calls value.format(format_spec).

New in version 2.6.


2022-09-22 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.