0

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.

Madhu
  • 1
  • 2

2 Answers2

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)

See: How to round a number to n decimal places in Java

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154