I thought I could accomplish this easily with something such as the following:
double numInput;
numInput = Double.parseDouble(inputTxtField.getText());
if ((numInput * 100) % 1 != 0) {
// do something
}
However, I'm getting all sorts of strange test cases where such as:
false: 2.11, 2.5, 2.6
true: 2.22, 2.3, 2.2
I just started programming so maybe this is a silly goof, but I thought multiplying a double by 100 and then checking for a remainder when dividing by 1 would work. The intent is to prevent someone from entering a number with more than two decimals. Less than or equal to 2 decimals is fine.
Any tips are appreciated! Thank you!
EDIT: Thank you for all the quick comments! This solved my problem, and I really appreciate the extra information as to why it won't work. Thank you!
Convert to BigDecimal
and check the scale
:
double[] values = { 2.11, 2.5, 2.6, 2.22, 2.3, 2.2, 3.141 };
for (double value : values) {
boolean fail = (BigDecimal.valueOf(value).scale() > 2);
System.out.println(value + " " + (fail ? "Fail" : "Pass"));
}
Output
2.11 Pass
2.5 Pass
2.6 Pass
2.22 Pass
2.3 Pass
2.2 Pass
3.141 Fail
Try
if(inputTxtField.getText().indexOf(".") >= 0 && inputTxtField.getText().indexOf(".") < inputTxtField.getText().length() - 2){
It will be true
when there is a decimal in the original String
that is before the last 2 characters in the String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With