I've got a really annoying task to do, and stuck with it. So: I need to write a function which gives back the value of a floating number after the decimal. For example: the param would be:5.456-> and the returning value should be:456.
I can not use String (of course this would be easy this way).
Do you have any suggestions?
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
;
int full = (int)d;
which will be 5d-full
will now be only the part after the point, so .456
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.