+ 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.

14th Jul 2020, 5:39 AM
Partha Jagdale
Partha Jagdale - avatar
9 ответов
+ 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
15th Jul 2020, 6:03 AM
Partha Jagdale
Partha Jagdale - avatar
+ 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! 😄
14th Jul 2020, 5:48 AM
WenHao1223
WenHao1223 - avatar
+ 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.
15th Jul 2020, 6:22 AM
Gordon
Gordon - avatar
+ 2
WenHao1223 Can you try this code snippet in code playground, and share yout result? print(round(1.5)) print(round(0.5))
15th Jul 2020, 5:13 AM
Gordon
Gordon - avatar
+ 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.
15th Jul 2020, 6:25 AM
Partha Jagdale
Partha Jagdale - avatar
+ 1
def mathRound(num): if.... : return.... else : return....
14th Jul 2020, 5:45 AM
Gordon
Gordon - avatar
- 1
Use casting technique.
14th Jul 2020, 1:50 PM
shubham kumar
shubham kumar - avatar