Reputation: 11211
Is it possible in Java to get the value of a double after the decimal point?
I want my code to produce an error message if the decimal part is 6 (like double number = 1.6
, or 2.6, or 98.6). If it is not 6, I just want to print "correct".
How do I retrieve the decimal part of the double?
Upvotes: 0
Views: 613
Reputation: 20059
Strictly speaking: Impossible - reason: double can never ever contain a fractional value of exactly .6 (No number ending in .6 is exactly representable as a double).
But you can check if the rounded String representation is .6:
DecimalFormat f = new DecimalFormat("#0.0");
String s = f.format(mydoublevalue);
if (s.contains(".6")) {
// error
} else {
// correct
}
Upvotes: 3
Reputation: 188
String stringNumber=""+number;
if(stringNumber.contains(".6"){
promt user
}
Upvotes: 1
Reputation: 562
You can floor the double, subtract that value from the double, and then have the fractional part left over for checking.
double number = 2.6;
double numberWholePart = Math.floor(number);
double numberFractionPart = number - numberWholePart;
if(numberFractionPart == 0.6) {
System.out.println("error!");
}
Upvotes: 0