Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check whether a double variable has more than two decimals in Java? [duplicate]

Tags:

java

decimal

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!

like image 289
Rumblebutt Avatar asked Sep 11 '15 20:09

Rumblebutt


2 Answers

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
like image 63
Andreas Avatar answered Sep 19 '22 06:09

Andreas


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.

like image 30
cbender Avatar answered Sep 23 '22 06:09

cbender