0

Consider I have the below list of float values. I import the locale United States to convert my comma decimal separator to dot decimal values. I cannot use the float format function before i convert it into dot values, since python don't accept comma values as float values. And when i also tried to use the float format function after i get the tuple of dot values, I wont be able to do so because tuples are immutable. I am need of all the tuple float values with a decimal precision of 2. It will be really great if someone can help me with it.

b=['1,374', '6,978', '3,987']

expected output :

b=((1.37), (6.97), (3.98))

Here is my code with output at every line

b= [(x,) for x in b]

output:

b=[('1,374', '6,978', '3,987')]

import locale
locale.setlocale(locale.LC_ALL,'English_United States.1252')
'English_United States.1252'
b=tuple(tuple(locale.atof(e.replace(',', '.')) for e in t) for t in b)

output:

b=((1.374), (6.978), (3.987))
scharette
  • 9,437
  • 8
  • 33
  • 67
sai
  • 13
  • 3
  • You simply want to change the decimals to two places at this point? Have you looked at https://stackoverflow.com/questions/15263597/convert-floating-point-number-to-a-certain-precision-and-then-copy-to-string? – Easton Bornemeier Jul 24 '18 at 14:46
  • You could try a lambda and map: `b=['1,374', '6,978', '3,987'] list(map(lambda x: (round(float(x.replace(',','.')),2),),b))` – whackamadoodle3000 Jul 24 '18 at 14:52

2 Answers2

1

Use a list comprehension. Replace the , then convert to float then round that value.

[round(float(x.replace(',','.')),2) for x in b]
[1.37, 6.98, 3.99]
W Stokvis
  • 1,409
  • 8
  • 15
1
b = ['1,374', '6,978', '3,987']
a = tuple( (float( v.replace(',', '.')), ) for v in b )

a
>>> ((1.374,), (6.978,), (3.987,))
xdze2
  • 3,986
  • 2
  • 12
  • 29
  • what is the locale did you use? I see that you have not used any locale to convert the decimal separator. – sai Jul 24 '18 at 15:12
  • no, the conversion is done "manualy" by `v.replace(',', '.')` (see the [doc](https://docs.python.org/3/library/stdtypes.html#str.replace))... maybe there is a more robust way to do this using a library dealing with locale, this [question](https://stackoverflow.com/q/13362121/8069403) seems a good start – xdze2 Jul 24 '18 at 18:40