44 Views

23rd June 2020

How To Round Up To 2 Decimal Places In Java?

I’m working on math.round() to round off this following code:

class round{
    public static void main(String args[]){
    double a = 123.13698;
    double roundOff = Math.round(a*100)/100;
    System.out.println(roundOff);
}
}

It returns 123, but I want it to be 123.14. It is required to be double for both input and output. Can anyone suggest an easy option?

 

Answers

23rd June 2020

Answered by Dikshit Jain

Hey Kusum,

To round up to 2 decimal places in java, use the below code, trust me it really works.

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

It returns 123.14

Or else, use the code below.

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

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos