Reputation: 343
I have the below json property which holds the numeric value
"creditLimit": "844500"
which has the following conditions:
Below are example valid inputs for which I want to throw a validation error message back to the user, saying invalid entry:
45500.00
9876543210
Example invalid inputs:
540.50
98765432109
When I tried
Double.valueOf(ent.creditLimit).intValue()
the final value alters, looks like it round off the value.
I do not want to keep the decimals.
How to retain the exact value? Thanks in advance
Upvotes: 0
Views: 315
Reputation: 13261
javax.validation
implementation in your classpath/runtime.In your JSON-Pojo, then:
@javax.validation.constraints.Pattern(regexp = "^\\d{1,10}$")
private String creditLimit;
Allows only numerical strings of length 1 to 10. Throws exception otherwise.
Upvotes: 1
Reputation: 13232
You could either use a regular expression to validate or you could parse as a BigDecimal then use intValueExact()
:
BigDecimal bd = new BigDecimal("540.50");
try
{
bd.intValueExact();
//number is a whole number
} catch(ArithmeticException e)
{
//number is not a whole number
}
Upvotes: 2