JasonG
JasonG

Reputation: 137

Python 3.6 rounding to 0.0

I am having a problem.I have the following code:

import json
import math


class Person:
    def __init__(self, first_name="", last_name="", age=0, height=0, weight=0):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.height = height
        self.weight = weight
        self.bmi = self.__bmi()

    def __bmi(self):
        a = (self.weight / math.exp(self.height)) * 703
        print(a)
        b = round(a, 1)
        return b

    def print_json(self):
        print(json.dumps(self.__dict__))


Jane = Person(first_name="Jane", last_name="Doe", age=35, height=72, weight=130)

Jane.print_json()

By executing the above code I get output:

4.916952131643318e-27
{"height": 72, "weight": 130, "age": 35, "bmi": 0, "last_name": "Doe", "first_name": "Jane"}

It keeps rounding 4.916952131643318e-27 to 0.0. I'm trying to round to 4.9.

Upvotes: 0

Views: 60

Answers (2)

17slim
17slim

Reputation: 1243

Wrote this as a comment, figured I may as well turn it into an answer.

4.9e-27 is a very small number (0.0000000000000000000000000049), so rounding to 1 digit is 0. Also, your BMI calculation looks way off anyway. math.exp(x) gives e to the x power. I believe you want (self.weight / (self.height**2)) * 703.

Upvotes: 4

Leonardo Gonzalez
Leonardo Gonzalez

Reputation: 1559

The number you are looking at is actually in scientific notation. Note the "e-27" -- that means it's actually 4.9 * 10^-27, or 4.9 divided by a 1 with 27 0s after it. This obviously is very, very close to zero.

Upvotes: 3

Related Questions