Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Rounding Numbers in Java

Options
  • 07-05-2001 2:13pm
    #1
    Closed Accounts Posts: 1,651 ✭✭✭


    Hey everyone.
    I'm trying to round numbers to two decimal places here, but this method doesn't seem to do anything. Can anyone here spot anything?
    Cheers!
    private double roundTwoDecimalDouble (double d)
       {
          int DECIMAL_PLACES = 2;
          java.math.BigDecimal bigDec = new java.math.BigDecimal(d);
          bigDec.setScale(DECIMAL_PLACES, java.math.BigDecimal.ROUND_HALF_UP);
          return bigDec.doubleValue();
       }
    


Comments

  • Closed Accounts Posts: 1,651 ✭✭✭Enygma


    Still don't know why that didn't work but came up with this instead and it works so I guess it's the *right* way to do it smile.gif
    private double round(double d)
    {
       int secondInt = 0;
       double finalDouble = 0;
       int tempInt = (int)(d * 1000);
       if ((tempInt % 10) >= 5)
       {
          secondInt = (int)((tempInt/10) + 1); 
       }
       else
       {
          secondInt = (int)(tempInt/10);
       }
       finalDouble = (double)secondInt;
       finalDouble = finalDouble / 100;
       return finalDouble;
    }
    
    

    Ugly but it works


  • Moderators, Music Moderators Posts: 1,481 Mod ✭✭✭✭satchmo


    You're right, that is ugly! tongue.gif
    Try this:
    double roundTwoPlaces(double d){
    	return Math.round(d * 100) /100.0;
    }
    


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    public static double round(int places, double number){
    c = Math.pow(10, places); // 10^places
    return ((int)(number*c))/c;
    }

    - Dead Bank Clerk -
    "Build a man a fire, and he'll
    be warm for a day. Set a man on
    fire, and he'll be warm for the
    rest of his life."


  • Moderators, Music Moderators Posts: 1,481 Mod ✭✭✭✭satchmo


    Doing a cast will always round it down (ie 1.109999 will round to 1.10 instead of 1.11), which isn't very desirable in most cases. You're better of using Math.round().


  • Closed Accounts Posts: 1,651 ✭✭✭Enygma


    Cheers lads!


  • Advertisement
  • Closed Accounts Posts: 1 psheehan


    change your to the following and it will work
    BigDecimal newDec=bigDec.setScale(DECIMAL_PLACES, BigDecimal.ROUND_HALF_UP);
    return newDec.doubleValue();




Advertisement