Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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.

2 Answers

+1 vote
by (46k points)

Well this one works...

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

Output is

123.14

Or 

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

this will do it for you as well.

0 votes
by (37.3k points)

Your current strategy has one major flaw: for the division (/100), you are using an integer division, which discards the decimal portion and returns an integer value. You need to ensure that this division is done in floating-point arithmetic by changing one of the operands to a double. That will fix it.

 This is how you change line 4:

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

This is the entire updated code:

class round{

    public static void main(String args[]){

    double a = 123.13698;

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

    System.out.println(roundOff);

}

}

This will provide you with the output 123.14.

Related questions

0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 9, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...