I create android app for dividing numbers.
int a,b;
int result = a/b;
if (result==decimal){
Log.v ("result","your result number is decimal")
} else {
Log.v ("result","your result number is not decimal")
}
How can I check if result
is a decimal?
Use the modulus operator to check if there is a remainder.
if(a % b != 0) Log.v("result", "The result is a decimal");
else Log.v("result", "The result is an integer");
You can use modulus division to check if a number is a decimal. Let's say you use modulo and divide the number by 1. If it is an integer (math, not java), the remainder should be 0. If it a decimal, it should be anything but 0. Take, for example, this snippet of code:
double number = 23.471;
if (number % 1 != 0)
{
System.out.print ("Decimal");
}
else
{
System.out.print ("Integer");
}
In this case, it would output "Decimal" because the remainder would not be equal to 0.
Now what would this look like in a full program? The simple program below should allow for number input and then output whether the number is an integer (in math) or decimal.
import java.util.*;
public class TestClass
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.print ("Enter a number: ");
double number = keyboard.nextDouble ();
if (number % 1 != 0)
{
System.out.print ("Your number is a decimal!");
}
else
{
System.out.print ("Your number is an integer!");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With