1

How do I parse strings as literal double values? I have a set of probability values I am parsing using Double.valueOf(probabilityString) that need to sum exactly to 1.0d.

For example, the resulting sum of the double values is 0.999999... when the probability strings are 0.2, 0.5, 0.2, 0.1.

What I would like to have is for the double values to be parsed in as 0.2d, 0.5d, 0.2d, 0.1d, is this possible?

I am dealing with a third-party library that accepts double[] as argument and throws an exception if the double values do not sum up precisely to 1.0d.

gewizz
  • 519
  • 2
  • 8
  • 16
  • You need something higher precision than floating point numbers then. That's just the way floating point numbers work. Certain numbers cannot be represented exactly, so summing those numbers will not give the result you expect. – Corbin Jun 07 '12 at 08:16
  • 1
    You need to assume that 0.9999999999999999 is so close to 1.0 it doesn't matter. – Peter Lawrey Jun 07 '12 at 08:26
  • Odd third party library that makes this assumption. – jontro Jun 07 '12 at 08:52

3 Answers3

4

doubles are only 64 bit long. There are an infinity of real numbers. It's thus impossible to represent exactly each real into a 64-bit double. So using doubles will always lead to approximated results. If you need absolute precision, use BigDecimal.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Use BigDecimal that is available in Java.

See this link, It will surely help you.

Let me know if you have any questions.

Community
  • 1
  • 1
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
0

try this:

DecimalFormat df =(DecimalFormat)NumberFormat.getInstance(); 
df.setParseBigDecimal(true); 
BigDecimal bd = (BigDecimal) df.parse(probabilityString);
Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75