Results 1 to 4 of 4
Like Tree1Likes
  • 1 Post By HansW

Thread: round to two decimal places

  1. #1
    javaMike is offline Member
    Join Date
    Nov 2007
    Posts
    5
    Rep Power
    0

    Default round to two decimal places

    is there an easy way to round a double to two decimal places?

    i.e. 1.98999 would round to 1.99

    the math.round method only rounds to nearest integer.

    decimalformat class converts number to a string.

    i figure there must be an easy way to do this...?? pls advise.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,577
    Rep Power
    7

    Default

    Java Code:
    double[] d = { 1.0/3.0, Math.PI, 2.0/3.0 };
    for(int j = 0; j < d.length; j++) {
        System.out.printf("d[%d] = %f%n", j, d[j]);
        double d2 = (int)Math.round(d[j] * 100)/100.0;
        System.out.printf("d2   = %f%n", d2);
    }

  3. #3
    HansW is offline Member
    Join Date
    Dec 2011
    Posts
    1
    Rep Power
    0

    Default Re: round to two decimal places

    Simple solution:

    (Math.round(d*100))/100
    Last edited by HansW; 12-23-2011 at 03:30 PM.
    quad64bit likes this.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Moderator
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    9,918
    Rep Power
    16

    Default Re: round to two decimal places

    Quote Originally Posted by HansW View Post
    Simple solution:
    Wrong. Not a solution at all.

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    And since this thread is over 4 years old, I'm closing it. If you have any questions, please start your own thread.

    db
    Why do they call it rush hour when nothing moves? - Robin Williams

Similar Threads

  1. rounding double to two decimal places
    By javaMike in forum Advanced Java
    Replies: 15
    Last Post: 03-10-2010, 12:04 AM
  2. Java calculator decimal
    By cart1443 in forum New To Java
    Replies: 2
    Last Post: 04-16-2008, 01:19 PM
  3. Capping decimal places
    By Rageagainst20 in forum New To Java
    Replies: 1
    Last Post: 12-20-2007, 09:28 PM
  4. Converts a binary number to a decimal
    By cachi in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 09:57 AM
  5. How to round a double?
    By Valeriano in forum New To Java
    Replies: 1
    Last Post: 05-31-2007, 03:50 PM

Posting Permissions

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