Decimal value issue
Solution 1:
It requires some steps to do it with primitives like float
or double
. If you were allowed to use BigDecimal
, this would just be one line of code.
Given double d = 5.456
;
- first, cut off the part before the floating point.
- do this by
int full = (int)d;
which will be 5 - the subtract full from it:
d-full
will now be only the part after the point, so.456
- do this by
- now use a loop to multiply the value by 10 until the "after the point" part is 0.
The special thing here is that when you use double, you have floating point precision issues. That means that d
will have the value 0.4560000000000004
in between. To solve that, let's introduce an epsilon.
The full code looks like this:
private static final double EPS = 1e-5;
public static void main(String[] args) {
double d = 5.456;
System.out.println(afterDot(d));
}
private static int afterDot(double d) {
d = getDecimals(d);
while(getDecimals(d) > EPS){ //decimals will likely never be 0 because of precision, so compare with a really small EPS instead of 0
d *= 10;
}
//cast the result to an int to cut off the double precision issues
return (int)d;
}
private static double getDecimals(double d) {
int full = (int) d;
d = d-full;
return d;
}
This prints 456
. I am very sure this can be optimized somehow, but it's a working first draft.
Solution 2:
What you want is the remainder, multiplied by 10 until the remainder is 0. Using BigDecimal
to prevent rounding issues that looks like this:
final BigDecimal input = new BigDecimal("5.456");
BigDecimal x = input.remainder(BigDecimal.ONE);
while (x.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) > 0) {
x = x.multiply(new BigDecimal(10));
}
System.out.println(x.longValue());