Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Java math api functio to round of a number to 2 digits

Status
Not open for further replies.

fixthebug2003

Programmer
Oct 20, 2003
294
US
HI,
Does anybody know the function to round off a numeric value to 2 decimal digits..

fixthebug2003
 
I don't think the question you're posing makes sense. Java keeps numbers as numbers and the only operative size is the number of bits. "Round" turns a float into an int. What I think you want to do is format a number as a string with 2 characters after the decimal point. I think the best thing to use is the DecimalFormat class of Java.text. You specify the pattern with # and 0, like "#,##0.00;-#,##0.00"

Bob Rashkin
rrashkin@csc.com
 
Code:
import java.text.DecimalFormat;
import java.text.NumberFormat;
class ro
      {
       public static void main(String args[])
              {
               double input = 12.056;
               double input2 = 43.4;
               String outputString1, outputString2;
               String pattern = "########0.00";               
               DecimalFormat outputBase = new DecimalFormat();
               outputBase.applyPattern(pattern);
               System.out.println("Result "+String.valueOf(outputBase.format(input2))); // String result has 2 d.p.
               System.out.println("ResultB "+Double.parseDouble(outputBase.format(input2))); // double result seems to have 1 d.p.

               // the following is another method for outputting the value with 2 d.p., the results may have 1 d.p.
               double output, output2;
               output = Math.round(input*100)/100d; // 100d is a must for a double result here
               System.out.println("output "+output);
               output2 = Math.round(input2*100)/100d; // 100d is a must for a double result here
               System.out.println("output2 "+output2);

              }
      }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top