I realized that Java does not provide any standard library method like isInteger() for the verification.
I came upon two good methods for checking if the user has entered an integer value or float value.
Solution 1:
--------------------------------------------------------------
String enteredNumber = "6.234";
double d=double.parseInt(enteredNumber);
if (Math.floor(d)==d) {
// d is an integer
}
else
{
// d's not an integer
}
--------------------------------------------------------------
Solution 2:
--------------------------------------------------------------
String enteredNumber = "6.234";
try {
int v = Integer.parseInt(enteredNumber);
valid = true;
// it's an integer
} catch(NumberFormatException e) {
valid = false;
//it's not an integer
}
--------------------------------------------------------------
Search
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Wednesday, April 23, 2008
To get the fractional portion of a number in Java
Problem:How do to get the fractional portion of a number in Java?
Suppose we have a number 4.56.
We need to get 0.56(fractional part) of it.
Solution:
double fraction(double d) {
if (d >= 0)
return d-Math.floor(d);
return d-Math.ceil(d);
}
Thanks to this link:
http://forum.java.sun.com/thread.jspa?threadID=752735&messageID=4301382
Suppose we have a number 4.56.
We need to get 0.56(fractional part) of it.
Solution:
double fraction(double d) {
if (d >= 0)
return d-Math.floor(d);
return d-Math.ceil(d);
}
Thanks to this link:
http://forum.java.sun.com/thread.jspa?threadID=752735&messageID=4301382
Subscribe to:
Posts (Atom)