0

The system of notation of decimal numbers in the Excel files I am dealing with is (I think) the European system (like French and German). So I have numbers like:

  • '23,4588'
  • '78,056888'

Note that they are in the form of strings. When I try to convert them to float python raises an exception:

>>> float('78,056888')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '78,056888'

Here's how I solve the problem:

 try:
     decim = int(excel_value)
 except ValueError:
     remap = {ord(','): '.'}
     decim = float(excel_value.translate(remap))

It seems to work as I want.

So my question is: is there a more appropriate python method for solving these kinds of problems?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Tobin
  • 2,029
  • 2
  • 11
  • 19
  • this one looks interesting: https://stackoverflow.com/a/7106835/11610186 (and the one below, in case if you specifically deal with ```pandas```) – Grzegorz Skibinski Oct 11 '19 at 21:24

1 Answers1

2

You can do this more succinctly with str.replace:

decim = float(excel_value.replace(',', '.'))
Kevin
  • 16,549
  • 8
  • 60
  • 74