Valueerror: Invalid Literal For Int() With Base 10: '1000.00'
Solution 1:
The general approach is correct, but int
is clearly wrong since apparently the amounts are expressed in "dollars.cents".
float
would appear to work but would probably not be the right choice: handling monetary amounts is instead the primary reason the decimal
module was added to the Python standard library! With decimal
you'll get precise computations, without the risk of rounding errors losing or gaining a cent here and there which would unchain The Auditors upon you.
So here's how I'd do it...:
import decimal
classBankAccount:
defset(self,balance=decimal.Decimal('0.00'):
self.balance = balance
# the rest of the class is fine. Shd probably have an __init__ tho.# also should keep an audit trail of deposit and withdrawals!def processAccounts(fname):
withopen(fname,'r') as f:
start_bal = decimal.Decimal(next(f).strip())
ba = BankAccount()
ba.set(start_bal)
for line in f:
fields = line.strip().split()
if fields:
if fields[0] in'Ww':
ba.withdraw(decimal.Decimal(fields[1])
elif fields[0] in'Dd':
ba.deposit(decimal.Decimal(fields[1])
else:
print('Ignoring line: {!r}'.format(line.strip()))
return ba
Solution 2:
First, since you are working with money the correct answer is to use the decimal
class as suggested by Alex Martelli.
Having said that, the answer to the specific problem of the ValueError
can be solved with a 3rd party module called fastnumbers (I am the author). It provides a function called fast_forceint
that will corerce strings of floats to (i.e. '1000.00') to an int
.
>>>from fastnumbers import fast_forceint>>>fast_forceint('1000.00')
1000
>>>isinstance(fast_forceint('1000.00'), int)
True
This library was specifically designed to ease the pain of converting strings to numeric types.
Solution 3:
To do so without using the decimal class (less accurate when working with floats), also including a constructor:
classBankAccount():
def__init__(self, initialBalance = 0):
self.accBalance = initialBalance
def__repr__(self):
return("BankAccount({})".format(self.accBalance))
defset(self, amount):
self.accBalance = amount
defdeposit(self, amount):
self.accBalance += amount
defwithdraw(self, amount):
self.accBalance -= amount
defbalance(self):
return(self.accBalance)
defprocessAccount(filename ):
withopen(filename,'r') as f:
b = BankAccount()
startBal = f.readline().split()
startBal = float(startBal[0])
b.set(startBal)
for line in f:
fields = line.strip().split()
if fields[0] in'Ww':
b.withdraw(float(fields[1]))
elif fields[0] in'Dd':
b.deposit(float(fields[1]))
return b
Post a Comment for "Valueerror: Invalid Literal For Int() With Base 10: '1000.00'"