'How to check if a given floating point number has numbers up till 1 decimal place in Java?
One of my friends asked to me to write a program that takes a floating point number and tells if it has numbers up till 1 decimal place. This is the program that I made:
class test
{
static void main(double a)
{
double test_a=100*a;
if(test_a%10==0)
System.out.println("The given number has numbers up till 1 decimal place");
else
System.out.println("The given number has number up till more than 1 decimal place");
}
}
How it works is if the given number has numbers up till 1 decimal place (say 4.6), 100 times that number gives a number divisible by 10 (4.6×100=460). But if the given number doesn't have numbers up till 1 decimal place (say 4.61), 100 times that number gives a number which isn't divisible by 10 (4.61×100=461). I used the same basis in my program above.
But it doesn't seem to work. For any floating point number, it outputs that "The given number has number up till more than 1 decimal place". But for integers, it outputs "The given number has number up till 1 decimal place".
Why is this really happening and how can I create this program ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
