Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding positive/negative numbers to nearest "whole" number

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.

like image 246
user1524705 Avatar asked Apr 19 '26 20:04

user1524705


2 Answers

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

like image 156
Joran Beasley Avatar answered Apr 21 '26 08:04

Joran Beasley


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!)
like image 30
mgilson Avatar answered Apr 21 '26 09:04

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!