Search code examples
pythontype-conversionmapreducemapper

How can i overcome a decimal place issue when using int(float(x)?


I have a csv file that I am using that is made up of several fields. I am adding the name fields - to get full name and then pulling out the price and qty fields - which are strings in the CSV file.

def mapper(self, key, value):
            fields = value.split(",")
            name = fields[6] + " " + fields[7]
            Price = int(float(fields[4]))
            Qty = int(fields[5])    
            avgPrice = (Price*Qty)
            yield name,avgPrice

my output is giving me

Becca Nelson 25.0

but i am missing the decimal places i think it is because I have had to use int(float(x)

I want the output to be Becca Nelson 25.55

How can i get around this?


Solution

  • You could use standard python module decimal to accurately process real values.

    from decimal import Decimal
    
    
    def mapper(self, value):
        fields = value.split(",")
        name = fields[6] + " " + fields[7]
        price = Decimal(fields[4])  # here
        qty = int(fields[5])    
        avg_price = price * qty
        return name, avg_price
    

    Also I'd recommend you use csv reader and pandas instead of string operations (example).