Results 1 to 5 of 5
  1. #1
    nat
    nat is offline Member
    Join Date
    Dec 2013
    Posts
    56
    Rep Power
    0

    Default Problem with rounding the integer type

    Hi,

    I have this code line:

    String sectionText = String.valueOf((int)percents.getYellowPercent());

    and I want the integer value to be displayed, instead of double. This works, but when the program rounds the double into integer, if the number is for example 75,56 (this is %) or 3,5 I would like it to be rounded in 76 (or 3,6 for the other example) since as it is at this moment, when all the calculated integers are summed, the result is not 100%, but 99%.

    Can anybody help me with this issue?

    Thanks

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Problem with rounding the integer type

    One way would be to add 0.5 to the double before casting it to int. (int)(1.2+.5) = 1 and (int)(1.5+.5) = 2
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Problem with rounding the integer type

    See also the Math class at Math (Java Platform SE 7 ). It has specific methods for rounding.

  4. #4
    nat
    nat is offline Member
    Join Date
    Dec 2013
    Posts
    56
    Rep Power
    0

    Default Re: Problem with rounding the integer type

    I solved it by using (int)Math.rint().
    Thank you to both of you anyway
    Last edited by nat; 03-12-2014 at 09:17 PM.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Problem with rounding the integer type

    How can I implement your suggestion
    You don't need to know what the value is before adding and casting.
    Try some small,sample programs to see what adding 0.5 and casting to int will do.

    If there is a problem, show the input and the desired output.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 6
    Last Post: 09-14-2012, 12:33 PM
  2. Double keeps rounding to integer?
    By LucienMontierre in forum New To Java
    Replies: 2
    Last Post: 06-29-2012, 05:12 AM
  3. Problem with rounding up in a school project
    By OlivierSillegue in forum New To Java
    Replies: 10
    Last Post: 02-13-2012, 03:10 AM
  4. Replies: 1
    Last Post: 01-02-2012, 11:16 PM
  5. Replies: 1
    Last Post: 04-19-2011, 04:32 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •