문제

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