简体   繁体   中英

How do I round numbers in Java?

For this program I am writing I am taking a user's input of minutes and rounding up to the next hour. For example:

  • 1 minute = 1 hour
  • 59 minutes = 1 hour
  • 60 minutes = 1 hour
  • 61 minutes = 2 hours
  • 119 minutes = 2 hours
  • 120 minutes = 2 hours
  • 121 minutes = 3 hours

What is a simple way of going about this? Thank you.

Assuming it's an integer that will truncate when divided, it's a simple matter of:

int hours = (minutes + 59) / 60;

The following table shows the results:

minutes                   hours
-------   ----------------------------------------
    1     (  1 + 59) / 60   ->    60 / 60   ->   1
   59     ( 59 + 59) / 60   ->   118 / 60   ->   1
   60     ( 60 + 59) / 60   ->   119 / 60   ->   1
   61     ( 61 + 59) / 60   ->   120 / 60   ->   2
  119     (119 + 59) / 60   ->   178 / 60   ->   2
  120     (120 + 59) / 60   ->   179 / 60   ->   2
  121     (121 + 59) / 60   ->   180 / 60   ->   3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM