0

I need help with my Python Flask application. I'm trying to give a user the result of a division that they specify, but it's not working. When the user submits "5" and "2" for example, it returns "2" instead of "2.5". I have no idea why it would do this.

Below is my code... can anybody figure out why this would happen?

from flask import Flask, session, render_template, request
app = Flask(__name__)
app.secret_key = 'wlFw0WP7SrNmAMF1wJaUSjWMTYdTay8EDIA3FPQhbo9c7wQ9rIdQrzJRzcN1o3mp'

@app.route('/',methods=['GET','POST'])
def index():
    [...]
    if request.method == 'POST':
        a = int(request.form['a'])
        b = int(request.form['b'])
        result = a/b
        return render_template('index.html',session=session,result=result)
    return render_template('index.html',session=session)

# Other routes omitted

if __name__ == '__main__':
    app.run(host='0.0.0.0')
  • 2
    possible duplicate of [Python division](http://stackoverflow.com/questions/2958684/python-division) – gengkev Apr 26 '15 at 02:44

3 Answers3

4

In Python 2, dividing an int by another int will perform integer division.

To get around this, you can multiply a by 1.0, converting it to a float, before dividing by b:

result = a*1.0/b

This should give you the expected 2.5 instead of 2.

sdamashek
  • 636
  • 1
  • 4
  • 13
0

add this line at the beginning of ur source code.

from __future__ import division
user3001937
  • 2,005
  • 4
  • 19
  • 23
  • http://stackoverflow.com/questions/7075082/what-is-future-in-python-used-for-and-how-when-to-use-it-and-how-it-works – user3001937 Nov 20 '14 at 09:19
-1

Depending on the version of Python you are using, the results may be different. See this question for more details. But in a nutshell, it looks like, in order for you to see a float result, you will need convert the numbers into floats first as the below

a = float(request.form["a"])
a = float(request.form["b"])
Suhas
  • 7,919
  • 5
  • 34
  • 54
Jjagwe Dennis
  • 1,643
  • 9
  • 13