Simkill
Simkill

Reputation: 345

Cannot use int on fractions. Workaround? Python

I am loading in random lines from a CSV into a class. I need the system to see one of those values as a number and not a string to use for calculations. This works fine for whole numbers.

class Weapon:
    def __init__ (self, name, value, damage, weight, properties, catagory, description):
        self.name = name
        self.value = int(value)
        self.damage = damage
        self.weight = weight
        self.properties = properties
        self.catagory = catagory
        self.description = description

I have a problem where if I try to use int on a fraction (for example 0.05) I get the following error:

    self.value = int(value)
ValueError: invalid literal for int() with base 10: '0.05'

What can I use instead of Int, or as well as int, to get it working?

Upvotes: 1

Views: 336

Answers (2)

cmd
cmd

Reputation: 5830

Use

from decimal import Decimal
int(Decimal(value))

Don't use floats, floats are ugly.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

Use int(float(value)) to first parse the string into a float, then convert to an int.

But of course, then 0.05 will be reduced to 0. If that's not OK with you, just use float(value).

Upvotes: 4

Related Questions