Www
Www

Reputation: 63

Comma as decimal point in python

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)

Upvotes: 2

Views: 4154

Answers (2)

itismoej
itismoej

Reputation: 1847

In Python 3.6+ you can use this:

>>> num = 1.201020
>>> f'{num:.2f}'.replace('.', ',')
'1,20'

For older versions, try using this:

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

Upvotes: 4

Samuel O.D.
Samuel O.D.

Reputation: 393

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

Upvotes: 0

Related Questions