Take the 2-minute tour ×

This question already has an answer here:

 double d = 4.321562;

Is there an easy way to extract the 0.321562 on it's own from d? I tried looking in the math class but no luck. If this can be done without converting to string or casting to anything else, even better.

share|improve this question

marked as duplicate by tcaswell, bummi, Vladimir, AlexVogel, Adam Arold Aug 30 '13 at 9:59


add comment

3 Answers

up vote 16 down vote accepted

Well, you can use:

double x = d - Math.floor(d);

Note that due to the way that binary floating point works, that won't give you exactly 0.321562, as the original value isn't exactly 4.321562. If you're really interested in exact digits, you should use BigDecimal instead.

share|improve this answer
add comment

Another way to get the fraction without using Math is to cast to a long.

double x = d - (long) d;

When you print a double the toString will perform a small amount of rounding so you don't see any rounding error. However, when you remove the integer part, the rounding is no longer enough and the rounding error becomes obvious.

The way around this is to do the rounding yourself or use BigDecimal which allows you to control the rounding.

double d = 4.321562;
System.out.println("Double value from toString " + d);
System.out.println("Exact representation " + new BigDecimal(d));
double x = d - (long) d;
System.out.println("Fraction from toString " + x);
System.out.println("Exact value of fraction " + new BigDecimal(x));
System.out.printf("Rounded to 6 places %.6f%n", x);
double x2 = Math.round(x * 1e9) / 1e9;
System.out.println("After rounding to 9 places toString " + x2);
System.out.println("After rounding to 9 places, exact value " + new BigDecimal(x2));


Double value from toString 4.321562
Exact representation 4.321562000000000125510268844664096832275390625
Fraction from toString 0.3215620000000001
Exact value of fraction 0.321562000000000125510268844664096832275390625
Rounded to 6 places 0.321562
After rounding to 9 places toString 0.321562
After rounding to 9 places, exact value 0.32156200000000001448796638214844278991222381591796875
share|improve this answer
+1 for accuracy. –  David May 29 '11 at 9:08
add comment

Use modulo:

double d = 3.123 % 1;
assertEquals(0.123, d,0.000001);
share|improve this answer
add comment
