gary00ie Posted February 26, 2012 Share Posted February 26, 2012 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 Quote Link to comment https://forums.phpfreaks.com/topic/257816-java-double-or-int/ Share on other sites More sharing options...
requinix Posted February 26, 2012 Share Posted February 26, 2012 Use doubles for everything, then round all numbers to some maximum degree of precision. 1 + 2 might turn out to be 2.999999999978 so you round and end up with 3. Quote Link to comment https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1321417 Share on other sites More sharing options...
gary00ie Posted February 26, 2012 Author Share Posted February 26, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1321470 Share on other sites More sharing options...
kicken Posted February 26, 2012 Share Posted February 26, 2012 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 } Quote Link to comment https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1321477 Share on other sites More sharing options...
thehippy Posted February 29, 2012 Share Posted February 29, 2012 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; } } Quote Link to comment https://forums.phpfreaks.com/topic/257816-java-double-or-int/#findComment-1322153 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.