Round Decimals

Discussion in 'Java' started by Jerry, Aug 9, 2005.

  1. Jerry

    Jerry Guest

    I wanted to round decimals. Usually, 1.6 would be rounded to 2 and 1.4
    will be rounded to 1. But I want 1.6 will be rounded to 2 and 1.4 will
    also be rounded to 2; for 2.1, it will be rounded to 3 and 2.6 will be
    rounded to 3. Tried to find such round function from javadoc, but was
    not able to find it. Anyone knows how to round the decimals according
    to the above rules?

    Thanks a lot!
     
    Jerry, Aug 9, 2005
    #1
    1. Advertisements

  2. Jerry

    Eric Sosman Guest

    It sounds like Math.ceil() may be what you want. If
    not, please describe your rounding rule as a rule, not
    just as a collection of examples.
     
    Eric Sosman, Aug 9, 2005
    #2
    1. Advertisements

  3. Lookup the javadoc of class java.lang.Math, method ceil(double)
     
    Thomas Fritsch, Aug 9, 2005
    #3
  4. Here's one way to do it:

    1. Convert to java.math.BigDecimal.

    2. Use setScale to round, with a specified rounding mode, either
    BigDecimal.ROUND_UP or BigDecimal.ROUND_CEILING.

    Up and ceiling treat negative numbers differently. Up rounds away from
    zero, so -1.5 would round to -2. Ceiling rounds towards positive
    infinity, so -1.5 would round to -1.

    Patricia
     
    Patricia Shanahan, Aug 9, 2005
    #4
  5. Jerry

    Jeff Schwab Guest

    Math.ceil() is the way to go, but just for grins:

    public int roundUp(double d) {
    int i = (int) d;
    return d == i ? i : i + 1;
    }
     
    Jeff Schwab, Aug 9, 2005
    #5
  6. Jerry

    prabhat143 Guest

    How about this.

    //let x be input value
    int y = Math.floor(x+1)

    prabhat
     
    prabhat143, Aug 10, 2005
    #6
  7. Rounding is usually expected to preserve numbers that are already
    rounded. If x is an integer, Math.floor(x+1) is x+1.

    Patricia
     
    Patricia Shanahan, Aug 10, 2005
    #7
  8. Add 0.5 to your decimal number and then convert it to an integer. This
    does what you want.
     
    frankgerlach22, Aug 12, 2005
    #8
  9. Jerry

    Jeff Schwab Guest

    What do you mean by "convert it to an integer?" If you convert by
    casting, 1.4 will get rounded to 1, not 2. If you convert by rounding,
    3.0 will get rounded to 4, not 3.
     
    Jeff Schwab, Aug 12, 2005
    #9
  10. OK, I did not read the OP message exactly. My proposal works for
    "normal" rounding. ceil() should be the right method...
     
    frankgerlach22, Aug 12, 2005
    #10
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.