Reputation: 9986
How to check a string is numeric positive and possibly a comma as decimal separator and two decimal places maximum.
Example
10.25 is true 10.2 is true 10.236 is false theres 3 decimal 10.dee is false
Upvotes: 2
Views: 6618
Reputation: 185
Use that returns true if is a positive integer and false if not.
public static boolean isPositiveInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
if (str.charAt(0) == '-') {
return false;
}
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
boolean isDigit = (c >= '0' && c <= '9');
if (!isDigit) {
return false;
}
}
return true;
}
Upvotes: 0
Reputation: 23273
If a string represents negative number then it must be prefixed with a minus sign, regardless of the precision, number format or decimal separator used:
if(string.equals("0.0") || !string.startsWith("-")) {
//string is positive
}
Upvotes: 4
Reputation: 10285
To check for numeric, use:
Double number = Double.parseDouble(string);
return number > 0;
**UPDATE:
For comma as seperator, you can use the following:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(string);
double d = number.doubleValue();
return number > 0;
Upvotes: 3
Reputation: 2976
Another option is to use BigDecimal:
import java.math.BigDecimal;
public class TestBigDecimal2 {
public static void main(String[] args) {
String[] values = { "10.25", "-10.25", "10.2", "10.236", "10.dee" };
for(String value : values) {
System.out.println(value + " is valid: " + checkValid(value));
}
}
private static boolean checkValid(String value) {
try {
BigDecimal decimal = new BigDecimal(value);
return decimal.signum() > 0 && decimal.scale() < 3;
}
catch (NumberFormatException e) {
return false;
}
}
}
Upvotes: 0
Reputation: 439
or you can use this regexp
^[0-9]*([,]{1}[0-9]{0,2}){0,1}$
if you want both comma and dot as allowed separator then
^[0-9]*([\.,]{1}[0-9]{0,2}){0,1}$
Upvotes: 6
Reputation: 17654
The correct way to get the sign of a number is to use signum
provided by Math
lib.
Math.signum(yourDouble);
Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero
Upvotes: 0
Reputation: 6043
My suggestion: Convert to a double first. That will test for numeric. If that fails; convert the last comma in a period (indexOf, replace). Then convert again.
For making sure you have 2 decimal places maximum - there's functions for that in DecimalFormat... But for alternatives, see this question here. Rounding a double to 5 decimal places in Java ME
After you have the double converted and stored to 2 decimal places, you can check if it's negative.
Upvotes: 0