Home > database >  Need to add another decimal space so the number has a .00 f.e., not .0
Need to add another decimal space so the number has a .00 f.e., not .0

Time:09-11

I am trying to create a simple trapezoid area calculator, but I need to upload it to a website to get graded and the site gives me no credit due to the fact that numbers have 1 less zeroes after the initial result, and they also don't round up if it happens to not give an exact number. How can I solve this problem?

b1 = float(input())
b2 = float(input())
h = float(input())
sq_area = (b1   b2) * h / 2
print(sq_area)

IMG of error.

CodePudding user response:

Here are the three dominant methods for formatted floating point in Python:

b1 = 10.0
b2 = 12.0
h = 2.3
sq_area = (b1   b2) * h / 2
print(f'{sq_area:.02f}', '{:.02f}'.format(sq_area), '%.02f' % sq_area)
       

Prints:

25.30 25.30 25.30

The methods:

  1. f'{sq_area:.02f} is an f string covered in PEP 498;
  2. '{:.02f}'.format(sq_area) using the .format string method covered in PEP 3101;
  3. '%.02f' % sq_area the legacy % operator with printf type formatting.

The f string method and .format method use Python's Format Mini Language and the % method uses a subset of specifiers similar to printf.

CodePudding user response:

Google f-string formatting and/or format specifiers. As this is clearly homework, I think it would be wrong to simply provide you with the answer.

As an alternative, f-string formatting in conjunction with padding might work, too.

  • Related