Question

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.

Was it helpful?

Solution

You could do this the safe way:

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

In this case, since strength is guaranteed to be a float, you can safely divide by 2 without worrying about truncation or importing division from __future__. As a bonus, you remove a huge security liability in your game as well.

Using input, a user could do some serious damage to your system:

RPG console> Input Strength Stat: __import__('os').system('rm -r ~')
                                 #^ User input (don't try this!)

OTHER TIPS

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

Alternatively, you could try:

from __future__ import division

in order to use py3k division. (e.g. result will be always float)

You may need to use Decimal to get the same rounding as RPG. With Decimal, you can set the rounding mode to up, down, half up, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top