Comma as decimal point in python

Question:

I am new to python.
In python, I wish to convert float variables to string variable with 2 decimal places and decimal comma.

For example, 3.1415 –> 3,14

it works fine. But when I convert 1.20, it gives 1,2 instead of 1,20.
I want the latter one
Is there an easy way to achieve that? Thank You Guys

My code is in the following:

s=float(input())
a=round(s,2)
x=str(a)
y=x.replace('.',','))
print(y)
Asked By: Www

||

Answers:

Try using this:

>>> num = 1.201020
>>> '{:.2f}'.format(num).replace('.', ',')
'1,20'
Answered By: Mohammad Jafari

You can easily get thousand an decimal separators using the format() function with the "f" format type.

var_float = 1234.5
str_float = "{:,.2f}".format(var_float)
print(str_float)
>> 1,234.50

However, format() doesn’t allow to configure the characters used as decimal and thousand separators. According to the docs:

This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped:

format(n, "6,f").replace(",", "X").replace(".", ",").replace("X", ".")

So in order to get your expected output you need to add replacements like these:

var_float = 1234.5
str_float = "{:,.2f}".format(var_float).replace(",", "X").replace(".", ",").replace("X", ".")
print(str_float)
>> 1.234,50

Other option is to set the appropriate locale so format() knows what characters to use. This requires the usage of the "n" format type, but you lose control over the number of decimal digits.

Example for the Spanish locale:

import locale
locale.setlocale(locale.LC_ALL, 'es_es')
var_float = 1234.5
print('{:n}'.format(var_float))
>> 1.234,5

Note that changing the locale will affect any future formatting.

More information on formatting in the docs

Answered By: Samuel O.D.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.