Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal mark when reading numbers as input

I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

like image 243
Till B Avatar asked Aug 18 '11 11:08

Till B


People also ask

How do you convert a number to a decimal format?

To convert a whole number into a decimal, you must decide the result to a certain number of places after the decimal point and simply add a decimal and the number of zeros required to the right side of the whole number. For example: Convert 5 into decimal to the hundredth place. Given that the whole number is 5.

How do you change the decimal separator in numbers?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes.

How do you input a decimal in Python?

When you want the user to type in a decimal use float(input()) , if you want the user to type in an integer use int(input()) , but if you want the user to type in a string use input() .


1 Answers

You may do it the locale-aware way:

import locale  # Set to users preferred locale: locale.setlocale(locale.LC_ALL, '') # Or a specific locale: locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")  print locale.atof("3,14") 

Read this section before using this method.

like image 86
Lauritz V. Thaulow Avatar answered Sep 18 '22 09:09

Lauritz V. Thaulow