Вопрос

I'm doing a project where I need to save some user input as a double, formatted to 4 decimal places. I can manage to get the string to have the right format, but parsing it to a Double breaks it. Here is an example of what i'm doing..

        DecimalFormat format = new DecimalFormat("#.0000");

    String example = "1.23";
    Double num = Double.parseDouble(example);

    String str = format.format(num);

    Double num1 = Double.parseDouble(str);

    System.out.println(num1);

this prints

1.23

when i'd like it to print

1.2300
Это было полезно?

Решение

You're confusing the number with the String representation of the number. These are two very different things. A floating point number has an accuracy, but it doesn't understand what display significant digits mean. It's like asking the abstract number 0 to know that 00 is.

To display the number correctly, use the formatter that you have already created:

System.out.println(format.format(num1));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top