How to format and parse Number using locale module














































How to format and parse Number using locale module



HOW TO FORMAT AND PARSE NUMBER

In Locale module we are given two specialized functions to parse a string into a number which is based on the current locale:
atof : it converts string into a floating point number which follows the LC_NUMERIC settings. Syntax for the following function is given below:
locale.atof(string)
atof : it converts string into an integer number which follows the LC_NUMERIC convention. Syntax for the following function is given below:
locale.atoi(string)
It is extremely useful for parsing a string that has a comma or dot, as different locales interpret it differently. For example:
locale.atof('32,824')
Here ,32,824 is 32824.00 for en_SG(English/SIngapore) and 32,824 is 32.824 for de_DE(German)

Further on, we can use the format_string() function to format a number according to your preferences. The following code is based on the de_DE locale:
locale.format_string('%10.2f', 738213.78)
locale.format_string('%10.2f', 738213.78, grouping=True)

We can set a grouping parameter for the format_string() function, which accepts a boolean(which is either True or False).

  • grouping (if it is set to True, it takes grouping into account; or, it will be  False by default).


Comments