junaidp
junaidp

Reputation: 11211

How do I check whether a double's decimal part contains a specific number?

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

Answers (4)

Durandal
Durandal

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

atredis
atredis

Reputation: 382

Try this:

if(number - Math.floor(number) == 0.6){
  prompt error
}

Upvotes: 0

ricgeorge
ricgeorge

Reputation: 188

String stringNumber=""+number;
if(stringNumber.contains(".6"){
promt user
}

Upvotes: 1

boztalay
boztalay

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

Related Questions