Using DecimalFormat to format large double numbers

I am trying to use DecimalFormatfor formatting double numbers, just to print a number with 2 decimal places, if it has a fractional else, I want to print the number as is. When the number is small, the code below works fine, but with large numbers, it does not work as expected.

    DecimalFormat df = new DecimalFormat("#.##"); //have tried just # too
    double d1 = 56789d;
    System.out.println(df.format(d1)); //works fine - prints 56789

    double d2 = 1234567879123456789d;
    System.out.println(df.format(d2)); // does not work

Second exits 1234567879123456770, but I want 1234567879123456789. For double values ​​with decimal, I just want to save two decimal points.

Any suggestions on what's going wrong?

+4
source share
2 answers

, 19, , double, IEEE 53 . , , , , 1. Math.ulp, " " double, .

double d2 = 1234567879123456789d;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(Math.ulp(d2));
System.out.println(df.format(d2));

256.0
1234567879123456770

, double , . 3.10.2 JLS double :

float double - , 32- 32- 64- IEEE 754 .

Unicode IEEE 754 valueOf Float Double java.lang.

Double.valueOf javadocs:

s " " ; " " , , double IEEE 754 [...]

, long, - .

long l2 = 1234567879123456789L;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(l2));

1234567879123456789
+7

19 , double 15.9 .

0

Source: https://habr.com/ru/post/1528867/


All Articles