0

Hi I am trying to divide 2 very large double numbers and result is known to be int only. I am getting result either 1 less or 1 more if I use Math.ceil or cast to int. What is the best way to do this.

I have tried type casting and Math.ceil function.

double num1=sum-totalsum;
double d=(num1*totalmul);

double diff=mul-totalmul;
double missing=d/diff;
double repeated=missing+num1;
System.out.println((int)Math.ceil(repeated)+" "+(int)Math.ceil(missing));

expected result is int. repeated and missing are always int.

hitesh
  • 449
  • 3
  • 11
  • 26
  • What do you mean by "divide 2 very large double numbers and result is known to be int only"? That the result of the division __will__ always be a natural number only or that you only __care__ about the value before the decimal separator? Because the first part is very unlikely due to the imprecision of `double`. Also, since you're using multiple unknown variables here, can you provide real examples/values? – Tom May 12 '19 at 11:12
  • result is always natural number. for d= 1.1809311961584165E39 diff=5.13448346155833E37 I am getting value for missing is 23.00000000000001 which should be 23.0. missing will always be natural number as per the pre condition/logic set in the program. How can I get the missing to 23.0 – hitesh May 12 '19 at 11:18
  • Can you provide values for all variables, so we can calculate the numbers as well? – Tom May 12 '19 at 11:31

1 Answers1

1

I believe what you're looking for is Math.round()

So:

System.out.println((int)Math.round(repeated)+" "+(int)Math.round(missing));
enerve
  • 63
  • 6
  • can we limit decimal points to 2 digit maximum in this operation double missing=d/diff; rather using Math.round operation – hitesh May 12 '19 at 13:54
  • not directly but try this: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary – enerve May 12 '19 at 15:11