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.

3
  • 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. Commented Jun 7, 2012 at 8:16
  • 1
    You need to assume that 0.9999999999999999 is so close to 1.0 it doesn't matter. Commented Jun 7, 2012 at 8:26
  • Odd third party library that makes this assumption. Commented Jun 7, 2012 at 8:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 There is an infinity of whole numbers and for each whole number there is an infinity of real numbers. ;)
0

Use BigDecimal that is available in Java.

See this link, It will surely help you.

Let me know if you have any questions.

Comments

0

try this:

DecimalFormat df =(DecimalFormat)NumberFormat.getInstance(); 
df.setParseBigDecimal(true); 
BigDecimal bd = (BigDecimal) df.parse(probabilityString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.