how to round 0.055 value to 0.06 in java. I have tried DecimalFormat but it returns 0.05
Asked
Active
Viewed 324 times
2
-
have you tried to use BigDecimal#setScale? – Ernusc Apr 13 '15 at 07:36
-
What is the variable type before rounding (String, double, BigDecimal etc.), is the type after rounding the same? – S. Pauk Apr 13 '15 at 07:36
-
I have float values before rounding but I tried with BigDecimal and DecimalFormat. It din't work – Prashant Kumar Apr 13 '15 at 07:39
-
All the solutions here works fine when the values are of double type but not when the values are of float type. – Prashant Kumar Apr 13 '15 at 08:16
-
So use BigDecimal.ROUND_UP instead of BigDecimal.ROUND_HALF_UP – newuserua_ext Apr 13 '15 at 08:20
5 Answers
2
A kind of trivial way
double d = 0.055;
d= Math.round(d* 100);
d= d/100;
System.out.println(d);

Loki
- 4,065
- 4
- 29
- 51
-
-
-
You may read this article http://java.dzone.com/articles/why, actually it was a bug http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675 which already fixed on java 7 – newuserua_ext Apr 13 '15 at 08:32
1
This is good for you ;
new BigDecimal(String.valueOf(0.055)).setScale(2, BigDecimal.ROUND_HALF_UP)

newuserua_ext
- 577
- 6
- 18
0
Try below code.
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(0.055);
double finalValue = (Double)df.parse(formate) ;
System.out.println(finalValue);
Output:
0.06
Reference Link : Double value to round up in Java
0
public static void main(String[] args) {
double d = 0.055;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
}
Output:
.06

Touchstone
- 5,575
- 7
- 41
- 48
0
round(0.055, 2); // returns 0.06
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}

seenukarthi
- 8,241
- 10
- 47
- 68

Rahul Thachilath
- 363
- 3
- 16