0

I got ValueError: could not convert string to float at line 66

grand_total = total_holdings + float(current_cash[0]["cash"])

Can anyone show me my mistake? current_cash[0]["cash"] returns a string. I used float() to convert it to a float but when I run flask run, I got this error. How can I convert it to a float?

Here is my index():

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    # Select owned symbols and it's amount
    portfolio_symbols = db.execute("SELECT shares, symbol FROM portfolio WHERE id = :id", id=session["user_id"])

    # Create temporary variables to store value of user's total of holdings and grand total
    total_holdings = 0
    grand_total = 0

    # Update each symbol's price and total
    for portfolio_symbol in portfolio_symbols:
        symbol = portfolio_symbol["symbol"]
        shares = portfolio_symbol["shares"]
        stock = lookup(symbol)
        total = shares * stock["price"]
        total_holdings += total
        db.execute("UPDATE portfolio SET price = :p, total = :t WHERE id = :id AND symbol=:s", p=usd(stock["price"]), t=usd(total), id=session["user_id"], s=symbol)

    # Update user's cash in portfolio
    current_cash = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])

    grand_total = total_holdings + float(current_cash[0]["cash"])

    # Print portfolio in index homepage
    updated_portfolio = db.execute("SELECT * from portfolio WHERE id=:id", id=session["user_id"])

    return render_template("index.html", grand_total=usd(grand_total), stocks=updated_portfolio, cash=usd(current_cash[0]["cash"]))
2

This will happen if you store cash in users table with usd format. The usd function should only be used for displaying. It turns it's argument into a string. That is likely what is causing the error. cash should be stored in the database as a number, not formatted with usd.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .