Rounding positive/negative numbers to nearest "whole" number

user1524705 picture user1524705 · Jul 13, 2012 · Viewed 9.6k times · Source

I'm trying to round numbers derived from cmath's divide function to a "whole" number, the results often being negative due to the nature of the program.

Example code:

strength = input("Input Strength Stat: ")
str_mod = round(strength/2)

However, the result of this is that it, due to an oddity in python, always returns closer to zero rather than further if, say str_mod prior to rounding ends up at something like -1.5 (resulting in -1 rather than -2 as desired)

This, since I'm trying to create an automatic derived stat calc script for a custom Pen and Paper RPG system, is not the desired behavior. What I desire is for the script to return, at -1.5, -2.0 upon rounding. I need to be able to do this while still rounding positive numbers up similarly.

Answer

Joran Beasley picture Joran Beasley · Jul 14, 2012

this is because you are getting a(truncated) int from strength/2

try strength/2.0

this is not an oddity with python but simply how most languages cast types for numbers

5/2 = 2

5/2.0 = 2.5