find decimal in a given number
How can i find decimal(dot) in a given number in java.
I am getting input from user, he may give intege开发者_开发知识库r or float value.
I need to find he entered integer or float, is it possible?
if yes could u tell me please.
-- Thanks
Assuming you got the digits of the number in a String
, it would be
String number = ...;
if (number.indexOf('.') > -1)
...
you can try with yourNumberString.indexOf(".")
. If it returns a number greater than -1 there's a dot in the input.
Anticipating your need, I would suggest that you use java.util.Scanner
for number parsing, and use its hasNextXXX
methods instead of dealing with parseInt
etc and deal with NumberFormatException
.
import java.util.*;
String[] inputs = {
"1",
"100000000000000",
"123.45",
"blah",
" "
};
for (String input : inputs) {
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("(int) " + i);
} else if (sc.hasNextLong()) {
long ll = sc.nextLong();
System.out.println("(long) " + ll);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("(double) " + d);
} else if (sc.hasNext()) {
System.out.println("(string) " + sc.next());
}
}
This prints:
(int) 1
(long) 100000000000000
(double) 123.45
(string) blah
You do not need to explicitly search for the location of the decimal point as some answers suggest. Simply parse the String
into a double and then check whether that double represents an integer value. This has the advantage of coping with scientific notation for doubles; e.g. "1E-10", as well as failing to parse badly formatted input; e.g. "12.34.56" (whereas searching for a '.' character would not detect this).
String s = ...
Double d = new Double(s);
int i = d.intValue();
if (i != d) {
System.err.println("User entered a real number.");
} else {
System.err.println("User entered an integer.");
}
Some other ways to do this:
given
String input = ...
the following evaluates to true if it's a decimal number
input.split(".").length == 2
or
input.matches(".+\\..+")
or
!input.matches("\\d+")
精彩评论