Precision iN Java
Results 1 to 5 of 5

Thread: Precision iN Java

  1. #1
    Senior Member
    Join Date
    Dec 2001
    Posts
    134

    Precision iN Java

    Hello Guys!!!
    I have a question for a precision in java.
    i am using

    double num=.349995953;

    now the thing is that i want to round of variable "num" to two decimal places. so that the value of num become .35

    I am not falimiar with how to set this precision, I wonder if any one can help me.
    Regards
    Harbir
    U get What U pay for.

  2. #2
    Senior Member
    Join Date
    Mar 2004
    Posts
    557
    Hi

    A quick (ugly) way of doing this would be the following:

    pseudo:

    1. double num2=num*100 (since you want to round to 2 decimal places)
    2. int rounded=round(num2)
    3. num=rounded/100.

    The code[1]:

    Code:
    // JDK1.0.2 
    public class divers {
      public static void main(String args[]){
        divers d = new divers();
        d.testRound();
        }
    
      public void testRound(){
        double r = round(3.1537, 2); 
        System.out.println(r); // output is 3.15
        }
    
      double round(double value, int decimalPlace) {
        double power_of_ten = 1;
        while (decimalPlace-- > 0)
           power_of_ten *= 10.0;
        return Math.round(value * power_of_ten) 
           / power_of_ten;
        }
      }
     
    //JDK1.1 
    import java.math.*;
    
    public class divers {
      public static void main(String args[]){
        divers d = new divers();
        d.testRound();
        }
    
      public void testRound(){
        double r = 3.1537;
        int decimalPlace = 2;
        BigDecimal bd = new BigDecimal(r);
        bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
        r = bd.doubleValue();
        System.out.println(r); // output is 3.15
        }
     }
    Cheers

    [1] http://www.rgagnon.com/javadetails/java-0016.html
    If the only tool you have is a hammer, you tend to see every problem as a nail.
    (Abraham Maslow, Psychologist, 1908-70)

  3. #3
    Senior Member
    Join Date
    Jul 2003
    Posts
    813
    http://java.sun.com/j2se/1.5.0/docs/...berFormat.html

    You need SDK 1.5.0 for this I think, maybe it works on 1.4.2 as well.
    /\\

  4. #4
    Custom User
    Join Date
    Oct 2001
    Posts
    503
    NumberFormat works on 1.4.2 as well - I've used it quite successfully before. The only thing about it is that it can be a bit annoying to set up...but I guess it's debatable whether Math.round(...) is any easier.

    ac

  5. #5
    Senior Member
    Join Date
    Dec 2001
    Posts
    134
    Thanx Guys
    U get What U pay for.

Posting Permissions

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