How to round a double to 2 decimal places?

0 votes

If the value is 300.1234, it should be formatted to 300.12. If it is 300, then it should be 300.00

Apr 26, 2018 in Java by sophia
• 1,400 points
191 views

2 answers to this question.

0 votes
public static double round(double val, int places) 
{
    if (places < 0) throw new IllegalArgumentException();

    long fact = (long) Math.pow(10, places);
    val = val * fact;
    long tmp = Math.round(val);
    return (double) tmp / fact;
}

answered Apr 26, 2018 by Akrati
• 3,150 points
0 votes
double value = 200.3456;
System.out.printf("Value: %.2f", value);

You can use either String.format()

String result = String.format("%.2f", value);

Or you can use DecimalForamat()

DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
answered Dec 11, 2018 by Sushmita
• 6,840 points

Related Questions In Java

0 votes
2 answers

How to round up a value to 2 decimal places?

double d = 2.34568; DecimalFormat f = new ...READ MORE

answered Aug 30, 2018 in Java by Sushmita
• 6,840 points
42 views
0 votes
1 answer

How to round any number to n decimal places in Java?

You can use setRoundingMode() method to get ...READ MORE

answered Apr 13, 2018 in Java by parth295
• 4,600 points
66 views
0 votes
1 answer

How can we display an output of float data with 2 decimal places in java? Please help

You can use the printf method, for ...READ MORE

answered Jun 4, 2018 in Java by Daisy
• 8,040 points
33 views
0 votes
1 answer

How can we format float to n decimal places ?

You may pass the float value: String.format("%.2f", floatVal); READ MORE

answered Jul 2, 2018 in Java by sophia
• 1,400 points
9 views
+5 votes
3 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,380 points

edited Nov 6, 2018 by Omkar 6,166 views
0 votes
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,050 points
1,622 views
0 votes
1 answer

What are the differences between getText() and getAttribute() functions in Selenium WebDriver?

See, both are used to retrieve something ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,050 points
4,325 views
0 votes
1 answer

Selenium JARS(Java) missing from downloadable link

Nothing to worry about here. In the ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,050 points
334 views
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,040 points
27 views
0 votes
2 answers

How to read a text file in Java?

You can use Scanner class to read ...READ MORE

answered Aug 9, 2018 in Java by parth295
• 4,600 points
41 views