I just discovered that:
round(3.5) = 4
while:
round(2.5) = 2
That is, when a number ends in .5 it sometimes rounds up (as it should) and sometimes rounds down.
I want to make a program that does some calculations, but it rounds them well, it is not worth it that 55.5 rounds it to 55 .
How can I do so that, given any number, the numbers that end in .5 are well rounded ?
It doesn't work for me ceil
because if the number is 2.4 it would round to 3 , which is not correct either.
I don't want to know why this happens, I want to know how to make code like this work well:
X=a*b , where a and b are 2 decimal numbers
print(round(X))
so that the user can see the rounded number, so it seems simple, but if it gives 14.5 it rounds me to 14 . And that is not rounding correctly in science.
Why this happens is explained in Why does Python 3 round() round 3.5 to 4 but 2.5 to 2? . Basically, Python 3 uses bankers rounding , that is, the banker's rounding, which consists of rounding
.5
to the nearest even number.If you want to control exactly what rounding you apply, use the module
decimal
with its optionsROUND_HALF_EVEN
,ROUND_HALF_UP
orROUND_HALF_DOWN
( there are more ):I leave you two solutions:
1. Use the Decimal package
2. Use the Math package
You can check the integer part of the number and based on that decide to round up or leave it as it is.
In the case that the number ends with .5, it
round
decides to round towards the number to the nearest even number, if the integer part is odd, it rounds to the nearest smaller even number. Therefore, if the number is odd, round up, otherwise leave it as it is.Or you can go for the other solution which is to check the decimal part, if it is equal to 5, just round up.
In code it would be
The truth is that it seems quite strange... You can try to control it with a
if(charAt(num) == '.5')
and have it do a forced rounding up with the following: