Bartek Bartek - 10 days ago 6
Java Question

The exception of rounding - DecimalFormat

I have a problem with rounding. If I view the text as it is all about but does not work on the conversion of type double

DecimalFormat df = new DecimalFormat("#0.00000");

private double getAc(double b, double h){
double Ac = b * h;
Ac = Double.valueOf(df.format(Ac));
return Ac;
}

Ac = getAc(0.5, 0.8);

System.out.println("Ac: " + Ac);


.

Exception:
Caused by: java.lang.NumberFormatException: For input string: "0,40000"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)


Rounding to five decimal places

Answer

Here it is a good example (Source):

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class Main {
  public static void main(String args[]) {
    double d = 123456.789045414114;
    DecimalFormat df = new DecimalFormat("#0.00000");
    DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

    dfs.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(dfs);
    System.out.println(df.format(d));
  }
}

EDIT:

DecimalFormat df = new DecimalFormat("#0.00000");
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);

    private double getAc(double b, double h){
        double Ac = b * h;
        Ac = Double.valueOf(df.format(Ac)); 
        return Ac;
    }

    Ac = getAc(0.5, 0.8);

    System.out.println("Ac: " + Ac);