Jump to content

Java: Double or int


gary00ie

Recommended Posts

Hi!

 

I am trying to make a simple calculator in Java.

 

I was wondering, if the user enters 1 + 2 - those are both integers.  But if they enter 1.2 + 2.2 those are doubles or floats.

 

How do I test for both?  Is there some way to declare the input as a double and if it is an int, then remove the.000 etc.?

 

 

Thanks in advance :)

Link to comment
https://forums.phpfreaks.com/topic/257816-java-double-or-int/
Share on other sites

Thanks for the reply.

 

The only problem is, I want to be able to add 1 + 1 = 2 and also 2.2 + 2.2 = 4.4.

I am using doubles now and getting 1 + 1 = 2.0.  Is there a way to distinguish if it is an int, then don't print the 2.0, just the 2?

 

Thanks again.

 

 

Link to comment
https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1321470
Share on other sites

I'm not sure the proper way to cast in java, but you can determine if a number has a decimal value by casting it to an int, and subtracting it from the original double.  If the result is 0 then there is no decimal value.

 

Something like:

if (answer-(int)answer == 0){
   //is int
} else {
   //is double
}

 

 

Link to comment
https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1321477
Share on other sites

Haven't touched java in awhile but can you use method overloading to do what you want?

 

public class Calculator {

  public double sum(double first, double second){
    return first + second;
  }

  public int sum(int first, int second){
    return first + second;
  }
}

Link to comment
https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1322153
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.