For eg. there is a float value 1345.1, then how do I check whether it has only one decimal place and not more than that?
Asked
Active
Viewed 831 times
-1
-
3is this a String representation of a float? Otherwise the value may not be exactly what you think it is anyway. If this is a String then just test the length after the dot. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Scary Wombat Jul 09 '20 at 06:58
-
Good point, I can do that. This is the String representation, so I can test the length after the dot. Thanks, this will work. – Shiv Jirwankar Jul 09 '20 at 07:00
1 Answers
1
Theoretically you cannot have a float number as precise as this, it always has more digits unless someone already rounded it for you. Is it the case? If that's the case I think you could parse it as a String and count the digits after the dot. I would do it like this:
float floatNumber = 24.04;
String floatAsString= String.valueOf(floatNumber);
int indexOfDecimal = floatAsString.indexOf(".");
if(floatAsString.substring(indexOfDecimal).length == 1) {return true;}

Simone Lungarella
- 301
- 1
- 4
- 15
-
1
-
How would it work with https://stackoverflow.com/questions/588004/is-floating-point-math-broken ? – Scary Wombat Jul 09 '20 at 07:27