+ 2
How do you round a float to an integer value?
How do you round a float number value to an integer number value? For example: 4.30 = 4; and 42.5 = 43 I want to know how to do this in code. Give a brief idea instead of the solution.
7 Antworten
+ 3
I have figured it out after a few methods. Gordon's idea was the best and it worked better.
With the built-inround function, there were afew errors as Gordon mentioned. Therefore this should (not entirely sure, thats why, should) be a flawless round function.
https://code.sololearn.com/cEd18l218AFb/?ref=app
+ 8
Partha Jagdale the easiest way is by using:
number = float(input())
print(round(number)
Default decimal place of round func is 0, you can manually set it by round(number, x) where x is the decimal places
FYI, pls go to : https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_func_round.asp&ved=2ahUKEwizv5qEhszqAhXOeisKHWTUA3sQFjABegQIDBAF&usg=AOvVaw3uOj37EjHC6NW3zN_s8Abc
Hope this helpful! Programming is fun! 😄
+ 3
Partha Jagdale Actually it is not flawless, the built-in round function follows `Banker's rounding`, which is handling all 0.5 in a specific way to avoid having an over-large sum. Explicitly, it rounds up and rounds down alternately, so that the rounded result is always an even number.
Bearing in mind that the built-in round function uses banker's rounding, if you want to use Maths rounding (always round up), it is better to define the function yourself.
+ 2
WenHao1223 Can you try this code snippet in code playground, and share yout result?
print(round(1.5))
print(round(0.5))
+ 2
Thats why the "should" is there. ; )
So basically each method has its ups and downs, but it's best to customize the code for our needs.
+ 1
def mathRound(num):
if.... :
return....
else :
return....
- 1
Use casting technique.