Advertisement
Advertisement


round up to 2 decimal places in java?


Question

I have read a lot of stackoverflow questions but none seems to be working for me. i am using math.round() to round off. this is the code:

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100;

    System.out.println(roundOff);
}
}

the output i get is: 123 but i want it to be 123.14. i read that adding *100/100 will help but as you can see i didn't manage to get it to work.

it is absolutely essential for both input and output to be a double.

it would be great great help if you change the line 4 of the code above and post it.

2013/10/07
1
203
10/7/2013 11:47:47 AM

Accepted Answer

Well this one works...

double roundOff = Math.round(a * 100.0) / 100.0;

Output is

123.14

Or as @Rufein said

 double roundOff = (double) Math.round(a * 100) / 100;

this will do it for you as well.

2013/12/05
440
12/5/2013 8:59:33 PM

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));
2012/07/28

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}
2012/07/28

BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
2013/10/20

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;
2012/07/28

Try :

class round{
public static void main(String args[]){

double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff);   }}
2015/03/16