0
double y1 = 0; double y2 = 0; double i = 0.025; double n = 2; double h1 = 2000; double h2 = 4000; y1 = Math.pow((1 + i), n) * h1; y2 = Math.pow((1 + i), n) * h2; double result = y1 + y2; System.out.println(result); 

I want the result as "6303.749999999999" but it gives me "6303.75". How can i solve it?

4
  • 4
    You want 6303.749999999999? Commented Oct 13, 2015 at 14:24
  • 3
    Possible duplicate of How to round a number to n decimal places in Java Commented Oct 13, 2015 at 14:25
  • Isn't that the same as wanting 0.999999999999 with code like: double a = 1? Commented Oct 13, 2015 at 14:29
  • why would you even want to print an incorrect result? Commented Oct 13, 2015 at 14:31

2 Answers 2

1

correct result should be (and it is) 6303.750000000000017069679003611781820568916563219777423023367655509563911228609889292329171439632773399353027343750000

Try to give a look at the BigDecimal class.

 BigDecimal i = new BigDecimal(0.025); int n = 2; BigDecimal h1 = new BigDecimal(2000); BigDecimal h2 = new BigDecimal(4000); BigDecimal y1 = ((BigDecimal.ONE.add(i)).pow(n)).multiply(h1); BigDecimal y2 = ((BigDecimal.ONE.add(i)).pow(n)).multiply(h2); BigDecimal result = y1.add(y2); System.out.println(result.toEngineeringString()); 
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that you are calculating the value 6303.75. if you add a statement where you subtract the value 0.000000000001 from the variable result then you will get the expected value 6303.749999999999.

The below code changes demonstrate how you can instead calculate 6303.749999999999:

public static void main(String[] args){ double y1 = 0; double y2 = 0; double i = 0.025; double n = 2; double h1 = 2000; double h2 = 4000; y1 = Math.pow((1 + i), n) * h1; y2 = Math.pow((1 + i), n) * h2; double result = y1 + y2; result -= (double)0.000000000001; // this line is the key to calculating the expected result System.out.println(result); } 

Output:

6303.749999999999

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.