0

I have a variable called "P", and I want to limit the decimal numbers of a float. The input consists of three lines. The first two lines contain the integer values "a" and "b", respectively. The third line contains the integer p that defines the desired precision. 0<a,b,P≤100 is guaranteed. I want to display the message: "The result of a by b is X.", replacing X with the value of dividing a / b, given to P decimal places.

Ex:

input(a) = 10
input(b) = 5
input(p) = 3
expected result: "2.000"

Ex:

input(a) = 9
input(b) = 3
input(p) = 1
expected result: "3.0"

My code: a = 10, b = 5, p = 2

a = float(input())
b = float(input())
P = int(input())
y = round(a / b, P)
print(f'{a} / {b} = {y}.')

output = 10 / 5 = 2.0.
expected output = 10 / 5 = 2.00.
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128

2 Answers2

0

The round() function does what it's supposed to. The problem is how you want to represent the number. If you always want two decimal digits, even if the number has less significant decimal digits (e.g. you want 1.50 printed instead of 1.5) then you'll have to format the number accordingly when printing:

print(f'{a} / {b} = {y:.{P}f}.')

Here .{P}f is a format specifier for printing a floating point number with exactly P decimal digits, no matter how many significant decimal digits it might have. For more info see the doc on format string syntax.

In fact, if you only need to print such number, your code could be simplified to avoid using round() entirely:

a = float(input())
b = float(input())
P = int(input())
print(f'{a} / {b} = {y:.{P}f}.')
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

Modify the result display:

print(f'O resultado de {a} por {b} é {y:.{P}f}.')
                                       ^^^^^^

10
5
2
O resultado de 10.0 por 5.0 é 2.000.
Corralien
  • 109,409
  • 8
  • 28
  • 52