www.webdeveloper.com
Results 1 to 6 of 6

Thread: round up float?

  1. #1
    Join Date
    Jul 2006
    Posts
    9

    round up float?

    hi everyone.

    I have searched the forum for an answer but couldn't find any.

    Is there a simple way to round up float so instead of getting 3,49875985 as a result I would get 3,5? or is there any other way to round up numbers like that without the float?

    thanks in advance.

  2. #2
    Join Date
    Nov 2008
    Location
    Akron, OH
    Posts
    233
    Built in function in Java API -
    http://java.sun.com/j2se/1.5.0/docs/...ndingMode.html
    http://java.sun.com/j2se/1.4.2/docs/api/

    Check the Method Summary.
    example
    Code:
    public class RoundTwoDecimalPlaces{
      public static void main(String[] args) {
        float num = 2.954165f;
        float round = Round(num,2);
        System.out.println("Rounded data: " + round);
      }
    
      public static float Round(float Rval, int Rpl) {
      float p = (float)Math.pow(10,Rpl);
      Rval = Rval * p;
      float tmp = Math.round(Rval);
      return (float)tmp/p;
        }
    }
    example
    src: http://www.roseindia.net/java/beginn...alPlaces.shtml
    Last edited by javawebdog; 12-19-2008 at 01:31 PM.
    javawebdog
    Two things to remember:
    "The only place success comes before work is in the dictionary."
    "It's more than just a matter of survival. It's a matter of sympathy, compassion, passion and style."

  3. #3
    Join Date
    Jul 2006
    Posts
    9
    thanks for your help

    I got another question though :P.

    is it possible to convert float to int?

  4. #4
    Join Date
    Aug 2005
    Location
    The Garden State
    Posts
    5,634
    Quote Originally Posted by atakado View Post
    is it possible to convert float to int?
    All primitive types are interchangeable. you just need to cast

    Code:
    float f = (float)your_int;
    but it does it without rounding.
    Acceptable Use | SQL Forum FAQ | celery is tasteless | twitter

    celery is tasteless - currently needing some UI time

  5. #5
    Join Date
    Jul 2006
    Posts
    9
    thanks
    Last edited by atakado; 12-20-2008 at 03:04 PM.

  6. #6
    Join Date
    Aug 2005
    Location
    The Garden State
    Posts
    5,634
    the loss of precision is normal, and you should make note of it since int's are only whole numbers.
    Acceptable Use | SQL Forum FAQ | celery is tasteless | twitter

    celery is tasteless - currently needing some UI time

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles