226

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.

ppeterka
  • 19,921
  • 6
  • 58
  • 74
Aayush Mahajan
  • 3,328
  • 6
  • 19
  • 31

12 Answers12

484

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.

Bharat Sinha
  • 12,727
  • 6
  • 35
  • 63
  • 7
    Could this be tweaked to round up to 3 or 5 decimal places ? – Muhammad Gelbana Jul 28 '12 at 14:20
  • 2
    It also works `double roundOff = (double) Math.round(a * 100) / 100;` – Rufein Dec 05 '13 at 12:59
  • +1 or `double roundOff = Math.round(a * 100) / 100.0;` – Peter Lawrey Apr 04 '14 at 15:34
  • 1
    @SiB floor(x + 0.5) is different to round(x) for just *one* value, the value immediately less than 0.5. This is because `0.49999999999999994 + 0.5` is `1.0` when it should be rounded down to `0.0` – Peter Lawrey Apr 04 '14 at 15:37
  • -1 multiplying by 100 will not work for too large numbers, as they will go out of range and will begin from lower limit. Answer by @amitchhajer is correct in this matter – Martin Asenov Feb 04 '15 at 19:11
  • @Martin Asenov you are correct. but the range for double in java is 2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double. Don't you think if your numbers are going out of range for doubles than the whole approach needs to be revisited? – Bharat Sinha Feb 04 '15 at 21:51
  • 2
    well yes, because it actually happened to me :) – Martin Asenov Feb 05 '15 at 13:18
  • 7
    Still wondering why no one mentioned new BigDecimal(123.13698).round(new MathContext(5)).doubleValue() – george_h Apr 16 '15 at 22:57
  • @SiB double roundOff = Math.round(a * 100.0) / 100.0 works fine. But, double roundOff = Math.round(a * 1.0) / 1.0 doesn't work. Why so? – Sumit Desai Nov 20 '15 at 10:02
  • it return zero for some values dont know why !! – Nowshad Aug 09 '16 at 11:31
  • @Muhammad Gelbana - Number of zeroes increases the position. Eg - (1000.0) / 1000.0 for 3 decimal round off. – Arunchunaivendan Nov 06 '17 at 21:48
  • 2
    ( Math.round(395.0349999999 * 100 ) / 100.0. ) will become 395.03. I can see why as 395034 is nearest long that is then divided by 100. However I think generally people would expect the result as 395.04. – Vishal Saxena Oct 03 '18 at 15:46
  • It works, but it looks sooooo ugly! I would expect something like `round(double, int=0)` for this purpose, it would be so much more readable... – The Godfather Mar 31 '19 at 06:24
  • 1
    @VishalSaxena if people expect the result to be 395.04 then they are simply wrong. 395.0349999999 is closer to 395.03, therefore 395.03 is the correct answer. – DodgyCodeException May 02 '19 at 16:55
  • How about `double roundOff = Math.rint(a * 100) / 100;` – DodgyCodeException May 02 '19 at 16:55
95
     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));
amitchhajer
  • 11,398
  • 5
  • 36
  • 51
  • it says `DecimalFormat cannot be resolved to a type` – Aayush Mahajan Jul 28 '12 at 13:36
  • 15
    did you import java.text.DecimalFormat; ? – amitchhajer Jul 28 '12 at 13:42
  • 2
    that works only if double number is not lesser then 1 and greater then -1 - when that happens it doesnt show 0. – lukaszrys Jul 02 '15 at 19:10
  • 1
    double doubleValue = 245; DecimalFormat df = new DecimalFormat("##.00"); System.out.println("value: " + Float.valueOf(df.format(doubleValue))); prints 245.0 not 245.00 – Anushree Acharjee Apr 07 '17 at 13:30
  • Decimal Format does not round off the last decimal value for any of its functions. The margin for the round off for all the functions is >5 but its supposed to be >4. Eg - 1.235 should round off to 1.24 but the DF formatting rounds it to 1.23 which is wrong. But Math.round is accurate. – Arunchunaivendan Nov 06 '17 at 21:46
  • No way it wont work. Question is for round off the value. Not only Formatting. Anyway if you want to use DecimalFormattter then you have to set RoundingMode to up or down. decimalFormatter.setRoundingMode(RoundingMode.UP); decimalFormatrer.setRoundingMode(RoundingMode.DOWN); – Morez Aug 17 '18 at 16:49
  • But what if you want to use the number afterwards? Parse it again? that's no viable option – martyglaubitz Nov 13 '18 at 12:02
  • @Ronnie it does round on Java 12.0.2. – Det Aug 06 '19 at 18:12
  • This is not rounding, for example 0.00005 with #.#### mask will be formatted just to zero – ali Oct 25 '19 at 11:36
  • It should be `DecimalFormat f = new DecimalFormat("0.00");` for some case like as `0.234` – Huy Nguyen Jan 27 '20 at 06:52
  • It's important to note the format that format function uses the Locale.getDefault() instance, so if you are planning a developer for different timezones you must be aware of every Regional format could be different. – Leonardo Sep 17 '20 at 19:23
  • @HuyNguyen you are right but it will not work properly.. i.e. i have value around 32.. and this will showing 3.2.. – Vivek Thummar May 25 '21 at 10:23
66
String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}
Arun
  • 1,499
  • 1
  • 13
  • 19
55
BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
Reimeus
  • 152,723
  • 12
  • 195
  • 261
13

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) ;
cybertextron
  • 9,225
  • 24
  • 86
  • 187
10

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
Shirishkumar Bari
  • 2,242
  • 1
  • 24
  • 33
  • 1
    You could also use `BigDecimal.ROUND_HALF_EVEN` to achieve a similar logic like `Math.round()` (1.204 = 1.20, 1.205 = 1.21). – zoku Oct 09 '17 at 14:06
10

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);   }}
Shyamkkhadka
  • 1,308
  • 2
  • 17
  • 28
9
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

Arun
  • 1,499
  • 1
  • 13
  • 19
5

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

            }
user1023
  • 73
  • 1
  • 6
3

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;
umläute
  • 23,410
  • 4
  • 50
  • 99
  • with `double roundOff = Math.round(a*100F)/100.f;` the output is even more messed up. it is: `123.13999938964844` – Aayush Mahajan Jul 28 '12 at 13:32
  • are you interested in printing the rounded number or in evaluating the rounded number (to do something with it)? if it is only printing, you should look up the documentation for println. if you are interested in the numbers, then i guess (without actually having confirmed) that the "messed" up output is actually correct, as it is the closes floating-point equivalent to "123.14" (check [this](http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems)) – umläute Jul 28 '12 at 13:47
1

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);
}
}
afrin216
  • 2,131
  • 1
  • 11
  • 17
-4
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.

hilaia
  • 1