I need to extract the decimal part of a float number, but I get weird results:
float n = 22.65f;
// I want x = 0.65f, but...
x = n % 1; // x = 0.6499996
x
I bit long but works:
BigDecimal.valueOf(2.65d).divideAndRemainder(BigDecimal.ONE)[1].floatValue()
Because not all rational numbers can be represented as a floating point number and 0.6499996...
is the closest approximation for 0.65
.
E.g., try printing first 20 digits of the number 0.65
:
System.out.printf("%.20f\n", 0.65f);
->
0.64999997615814210000
edit
Rounding errors, which accumulate during computations, also play a part in it, as others noted.
Try java.math.BigDecimal.
Try this. If timer is 10.65 then h ends up as the first two decimal places * 100 = 65.
This is a quick and easy way to separate what you want without the rounding issues.
float h = (int)((timer % 1) * 100);
I think this would be the most simple way :
float n = 22.65f;
float x = n - (int) n;
This code will work for any number of decimal digits.
float f = 2.3445f;
String s = Float.toString(f);
char[] c = s.toCharArray();
int length = s.length();
int flag = 0;
StringBuilder n = new StringBuilder();
for(int i = 0; i < length; i++)
{
if(flag == 1)
{
n.append(c[i]);
}
if(c[i] == '.')
{
flag = 1;
}
}
String result = n.toString();
int answer = Integer.parseInt(result);
System.out.println(answer);