How do I get the part after the decimal point in Java?

I have a double variable d = 1.15.

I want the number after the decimal point, i.e. "15".

What is best way to achieve this in Java?

I have tried like this:

Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));

But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.


Solution 1:

try this,

String numberD = String.valueOf(d);
        numberD = numberD.substring ( numberD.indexOf ( "." ) );

Now this numberD variable will have value of 15

Solution 2:

Try Math.floor();

double d = 4.24;
System.out.println( d - Math.floor( d )); 

To prevent rounding errors you could convert them to BigDecimal

    double d = 4.24;
    BigDecimal bd = new BigDecimal( d - Math.floor( d ));
    bd = bd.setScale(4,RoundingMode.HALF_DOWN);
    System.out.println( bd.toString() );

Prints 0.2400

Note that the 4 in setScale is the number of digits after the decimal separator ('.')

To have the remainder as an integer value you could modify this to

BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );

Prints 24

Solution 3:

The number after the decimal point is not a well defined concept. For example for "4.24", it could be "0.24", "0.239999999999" (or similar), "24" or "239999999999".

You need to be clear if you are talking about a number or a string of decimal digits ... and whether the input value is a representation of a binary floating point number (in which case "4.24" is most likely an approximation) a decimal floating point number.

Depending on your interpretation, the correct answer will be different.


But i didn't get the proper answer because when I converted d.toString() the answer is 14.999999999999986.

You are running up against the problem that double and float are base-2 floating point formats, and in most cases they CANNOT represent decimal floating point numbers precisely. There is no fix for this ... apart from using something like BigDecimal to represent your numbers. (And even then, some loss of precision is possible whenever you do a division or modulo operation.)

Solution 4:

Try out RegEx, here ^\d*\., will search for digits followed by dot and replace with blank.

for(double d : new double[]{1.15,0.009,222.9,3.67434}){
    System.out.println(String.valueOf(d).replaceAll("^\\d*\\.",""));
}

gives:

15
009
9
67434

Solution 5:

If you want the decimal places and you want to round the result.

double d = 4.24;
System.out.printf("%0.2f%n", d - (long) d);

prints

0.24

If you want a rounded value, you have to determine what precision you want.

double d = 4.24;
double fract = d - (long) d;
fract = (long) (fract * 1e9 + 0.5) / 1e9; // round to the 9 decimal places.