-1

I'm trying to make a simple program in python that shows me the numbers 1.0, 1.1 up to 2. This is the code

test = 1.0

while True:
  print(test)
  test += 0.1
  if test > 2.1:
    break

Output:

1.0
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
1.6000000000000005
1.7000000000000006
1.8000000000000007
1.9000000000000008
2.000000000000001

Expected output:

1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2.0
DAme
  • 697
  • 8
  • 21
Solpip
  • 41
  • 8

2 Answers2

1

Use just float precision

print(f'{test:.1f}')

You don't need to use it while True or break. Use instead

test = 1.0
while test <= 2.1:
    print(f'{test:.1f}')
    test += 0.1

UPDATE: Set your own precitation how much you want. Nomarlly you can set upto 15 point precitation order. Example you want to divide test = 22/7:

print(f'{test:.2f}') -> 3.14
print(f'{test:.2f}') -> 3.142
print(f'{test:.2f}') -> 3.1428
...............................
print(f'{test:.15f}') -> 3.142857142857143
mhhabib
  • 2,975
  • 1
  • 15
  • 29
1

Printing a float with one decimal place outputs the float with one digit after the decimal point. For example, printing 3.14159 with 3.1. Use str.format(), with "{:.1f}" as str

test = 1.0

while True:
  print("{:.1f}".format(test))
  test += 0.1
  if test > 2.1:
    break

Output :

1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2.0
Sahadat Hossain
  • 3,583
  • 2
  • 12
  • 19