round up to 2 decimal places in java?

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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) ;

Solution 6 - Java

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

should be

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

Adding 'D' to 100 makes it Double literal, thus result produced will have precision

Solution 7 - Java

I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00") or using Math.round(a * 100) / 100 .

import java.math.BigDecimal;

public class RoundingNumbers {
    public static void main(String args[]){
        double number = 123.13698;
        int decimalsToConsider = 2;
        BigDecimal bigDecimal = new BigDecimal(number);
        BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with setting scale = "+roundedWithScale);

        bigDecimal = new BigDecimal(number);
        BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);

    }
}

This program would give us below output

Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14

Solution 8 - Java

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);   }}

Solution 9 - Java

This is long one but a full proof solution, never fails

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

if 4.25, Output 4.25

if 4.20, Output 4.20

if 4.24, Output 4.20

if 4.26, Output 4.30

if you want to round upto 2 decimal places,then use

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

if up to 3 places, new DecimalFormat("#.###")

if up to n places, new DecimalFormat("#.nTimes #")

 public double roundToMultipleOfFive(double x)
            {
                
                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }
               
                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;
                
                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }
                
                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));
                
            }

Solution 10 - Java

seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:

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

Solution 11 - Java

I just modified your code. It works fine in my system. See if this helps

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

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

    System.out.println(roundOff);
}
}

Solution 12 - Java

public static float roundFloat(float in) {
	return ((int)((in*100f)+0.5f))/100f;
}

Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAayush MahajanView Question on Stackoverflow
Solution 1 - JavaBharat SinhaView Answer on Stackoverflow
Solution 2 - JavaamitchhajerView Answer on Stackoverflow
Solution 3 - JavaArunView Answer on Stackoverflow
Solution 4 - JavaReimeusView Answer on Stackoverflow
Solution 5 - JavacybertextronView Answer on Stackoverflow
Solution 6 - JavaArunView Answer on Stackoverflow
Solution 7 - JavaShirishkumar BariView Answer on Stackoverflow
Solution 8 - JavaShyamkkhadkaView Answer on Stackoverflow
Solution 9 - Javauser1023View Answer on Stackoverflow
Solution 10 - JavaumläuteView Answer on Stackoverflow
Solution 11 - Javaafrin216View Answer on Stackoverflow
Solution 12 - JavahilaiaView Answer on Stackoverflow