Possible Duplicate:
round double to two decimal places in java
I want to round up the double value upto 2 decimal points.
for example: I have double d=2; and the result should be result =2.00
This question is related to
java
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
I guess that you need a formatted output.
System.out.printf("%.2f",d);
import java.text.DecimalFormat;
public class RoundTest {
public static void main(String[] args) {
double i = 2;
DecimalFormat twoDForm = new DecimalFormat("#.00");
System.out.println(twoDForm.format(i));
double j=3.1;
System.out.println(twoDForm.format(j));
double k=4.144456;
System.out.println(twoDForm.format(k));
}
}
public static double addDoubles(double a, double b) {
BigDecimal A = new BigDecimal(a + "");
BigDecimal B = new BigDecimal(b + "");
return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
Math.round(number*100.0)/100.0;
you can also use this code
public static double roundToDecimals(double d, int c)
{
int temp = (int)(d * Math.pow(10 , c));
return ((double)temp)/Math.pow(10 , c);
}
It gives you control of how many numbers after the point are needed.
d = number to round;
c = number of decimal places
think it will be helpful
This would do it.
public static void main(String[] args) {
double d = 12.349678;
int r = (int) Math.round(d*100);
double f = r / 100.0;
System.out.println(f);
}
You can short this method, it's easy to understand that's why I have written like this.
Source: Stackoverflow.com