I have tried to make the double value as round to the 2 precision values.I got it by using Date Format, but it is in String. How to make the double value as round to the precision without using Date Format.
Asked
Active
Viewed 1,085 times
0
-
3Please provide your code in question... – webcoder Oct 16 '13 at 07:14
-
5Do you want to round the printed value (for display purposes) or the variable itself (for calculation purposes) – Richard Tingle Oct 16 '13 at 07:15
-
share your scenario plz , do you want something like this ??http://stackoverflow.com/a/12190890/1283215 – Hussain Akhtar Wahid 'Ghouri' Oct 16 '13 at 07:16
-
Maybe BigDecimal is your choise? Doubles are not very good with true rounding. – Leonidos Oct 16 '13 at 07:19
2 Answers
1
here is the example
public class RoundValue
{
public static void main(String[] args)
{
double kilobytes = 1205.6358;
System.out.println("kilobytes : " + kilobytes);
double newKB = Math.round(kilobytes*100.0)/100.0;
System.out.println("kilobytes (Math.round) : " + newKB);
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes));
}
}
output:
kilobytes : 1205.6358
kilobytes (Math.round) : 1205.64
kilobytes (DecimalFormat) : 1205.64

Pratik
- 30,639
- 18
- 84
- 159
-
Does not round, so not an answer, and the technique [does not work in general](http://stackoverflow.com/a/12684082/207421). – user207421 Oct 16 '13 at 08:50
0
As EJP and Leonidos said in comments, proper rounding is performed through the BigDecimal class not the double
primitive.
Carefully choose your rounding mode. Banker's Rounding is a common way to break ties (even splits), though the best way depends on your purpose and situation.
double d = 7.345;
java.math.BigDecimal bigDecimal = new java.math.BigDecimal(d).setScale(2, java.math.RoundingMode.HALF_EVEN);
System.out.println("My big decimal is: " + bigDecimal ); // Outputs: 7.34 (using Banker's Rounding)

Community
- 1
- 1

Basil Bourque
- 303,325
- 100
- 852
- 1,154