0

I am currently rounding numbers with floating decimals in python. I thought that the numbers were being rounded UP to a whole integer but, I am suspicious...

What is the best way to ensure a rounding UP to the nearest whole integer?

Data for "snw" variable:

0
0
0
1.5
0
0.5
0
1
1
0
0
0
0
0
0
0
0
0
1

Python Code:

for i in range(len(snw)):
    fmt=r"%5.0f" % (snw[i])
arnpry
  • 1,103
  • 1
  • 10
  • 26
  • what outcomes are you getting? – WhatsThePoint Jan 06 '17 at 15:06
  • 1
    Possible duplicate of [How do you round UP a number in Python?](http://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python) – Tagc Jan 06 '17 at 15:08
  • Hi @WhatsThePoint, the outcomes are values that appear to be rounding down instead of up. i.e., `0.5` rounding down to `0` instead of `1`. – arnpry Jan 06 '17 at 15:26
  • python will always round `0.5` down unless you specify it to go up, anything above it will always go up – WhatsThePoint Jan 06 '17 at 15:30

1 Answers1

0

It's unclear exactly what behaviour you are aiming for.

If you would like to round all numbers up (i.e. 0.1 to 1), then the easiest option is to call math.ceil:

>>> import math
>>> math.ceil(0.1)
1.0
>>> r"%5.0f" % math.ceil(0.1)
'    1'

On the other hand if you want to change how ties are handled (i.e. numbers with a fractional part of 1/2), and if you're using Python 2, you can use round:

>>> round(0.5)
1.0
>>> r"%5.0f" % round(0.5)
'    1'

Note however that Python 3 changed the behaviour of round to use "ties to nearest even", so in that case you would need to do something else. My favourite is the following:

import math
def oldround(x):
    y = x - math.trunc(x)
    return math.trunc(x+y)
Simon Byrne
  • 7,694
  • 1
  • 26
  • 50