0

I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double values and performing an operation on them.

The poblem is that the output is always double. I would like to have the answer to be an integer answer if the result is an integer, say, 2 instead of 2.0.

Cases:

  1. A= 2 and B= 2 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4

  2. A= 2.0 and B= 2.0 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4.0

I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float to int, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly.

Thank you

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Ashish Kumar
  • 166
  • 8
  • Even if the mathematical value is an integer, the result of a calculation with floating point numbers may not be (due to rounding errors). – Henry Sep 28 '20 at 10:54
  • @Henry yeah I read through those problems, I might change my code later. That's why I didn't focus on operator/operation part, just looking for conversion paths possible for me to take here. – Ashish Kumar Sep 28 '20 at 11:01
  • 1
    The point is that converting a floating point value to an integer to make it look pretty is *mathematically unsound*. You shouldn't do it. And if "the boss" asks you to, you should explain the mathematics to him (or her) in order to convince him that the pretty answer is a wrong answer. – Stephen C Sep 28 '20 at 11:05
  • Does this help? https://stackoverflow.com/questions/9898512/how-to-test-if-a-double-is-an-integer – Abra Sep 28 '20 at 11:06
  • @StephenC that's so true haha. – Ashish Kumar Sep 28 '20 at 11:13
  • @Abra thank you that works. little bit of wordings here and there (-_-). I swear it didn't even pop up as suggestion when I was posting this question. – Ashish Kumar Sep 28 '20 at 11:17
  • For your case two, you just cannot go through the Double data type because the decimal information will be lost. What about using a BigDecimal instead? – matt Sep 28 '20 at 11:20

1 Answers1

1

You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.

double num1 = 20.0;
double num2 = 5.0;
    
if (num1%num2 == 0) {
    System.out.println((long) (num1/num2));
} else {
    System.out.println(num1/num2);
}
Solomon Kariri
  • 567
  • 4
  • 4