0

Some examples:

double a = Double.parseDouble("53.82233040000000557");
System.out.println(a);
output: 53.822330400000006

double b = Double.parseDouble("53.82274970000000280");
System.out.println(b);
output: 53.8227497

Why are they getting rounded and how can I prevent this from happening?

dYTe
  • 191
  • 1
  • 8
  • You can use a BigDecimal instead if you really need that accuracy – Felix Oct 23 '17 at 13:23
  • 1
    You've left out an important thing above: How you're getting that output. – T.J. Crowder Oct 23 '17 at 13:24
  • ...but assuming you're using something that outputs the double as a string: The standard way to converting IEEE-754 floating point numbers to strings is to only output as many digits as are needed to differentiate the actual value of the number from the values on either side of it that can be represented. So even though the number may have more significant places than `53.8227497`, only `53.8227497` is needed to differentiate that number from the representable ones on either side. – T.J. Crowder Oct 23 '17 at 13:29
  • I got the output by using System.out.println(). – dYTe Oct 23 '17 at 13:32
  • The default conversion for printing a double is `Double.toString`. For each double X, there is a set of decimal fractions that parseDouble would convert to X. toString picks the shortest. You can get the full story, with no rounding, using `System.out.println(new BigDecimal(b));`. More usefully, you can use `DecimalFormat ` to control how many digits are displayed. – Patricia Shanahan Oct 23 '17 at 16:54

0 Answers0