0

Consider:

def välgu_kaugus(aeg):
    kiirus = 300 / 1000
    valem = aeg * kiirus
    return valem
print(välgu_kaugus(float(input("Mitu sekundid kulus välgu nägemiseks müristamise kuulmiseni? "))))

This is my little shitty program. When I input 15 it gives me 4.5, but I want it to round 4.5 to 5, but using the round command it rounds my 4.5 to 4 for some reason. How can I make it to round to 5?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Marek Lindvest
  • 71
  • 1
  • 1
  • 3
  • Take a look at https://docs.python.org/3/library/math.html –  Nov 06 '16 at 18:17
  • The suggested duplicate isn't one, really; the effect the OP is seeing is due to Python 3's round behaviour for halfway cases (i.e., it rounds ties to the nearest even integer), along with the lucky accident that `300 / 1000 * 15` *is* exactly a halfway case. – Mark Dickinson Nov 06 '16 at 21:08
  • See http://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python for more. – Mark Dickinson Nov 06 '16 at 21:08

2 Answers2

1

Use round(). For example:

>>> round(4.5)  # Your number, rounded to ceil value
5.0
>>> round(4.3)  # rounded to floor value
4.0
>>> round(4.7)  # rounded to ceil value
5.0
Anonymous
  • 40,020
  • 8
  • 82
  • 111
0

Solution to your problem is to use ceiling.

import math
print math.ceil(4.5) // 5

Here are some references on how to round a number in python: https://www.tutorialspoint.com/python/number_round.htm

How do you round UP a number in Python?

Community
  • 1
  • 1
develop1
  • 727
  • 1
  • 8
  • 29