Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if number is a decimal?

Tags:

java

android

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?

like image 988
Ash Avatar asked Dec 01 '22 04:12

Ash


2 Answers

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");
like image 159
Montycarlo Avatar answered Dec 02 '22 17:12

Montycarlo


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!");
        }
    }
}
like image 31
Elizabeth Avatar answered Dec 02 '22 16:12

Elizabeth