Search code examples
stringpython-3.5scientific-notation

How do I fix this error: "ValueError: could not convert string to float: '-1,89E-09'"?


I want to plot numbers in scientific notation by reading and putting these numbers in y-list. Here is my code.

import matplotlib.pyplot as plt
import csv

x = []
y = []


with open('test1.txt','r') as csvfile:
     plots = csv.reader(csvfile, delimiter='\t')  
        for row in plots:
        x.append(float(row[0]))
        y.append(float(row[1]))


  plt.plot(x,y, label='20 Volt max with filter')
  plt.xlabel('time')
  plt.ylabel('voltage')
  plt.show()

The .txt file looks like this:

0   -1,89E-09
0,001   -1,37E-08
0,002   -5,69E-08

The error is:

ValueError: could not convert string to float: '-1,89E-09'

Solution

  • In Python and many other languages, the standard decimal separator is . (period) not , (comma).

    From Decimal Mark on Wikipedia:

    In 1958, disputes between European and American ISO delegates over the correct representation of the decimal mark nearly stalled the development of the ALGOL computer programming language. ALGOL ended up allowing different decimal marks, but most computer languages and standard data formats (e.g. C, Java, Fortran, Cascading Style Sheets (CSS)) specify a dot.

    You can change the format used in your text file, or you could float(row[n].replace(",", ".")).