I\'m using a float constant and setting a objects private float variable to the float constant below, but when the object outputs the value it was set to, it\'s rounding up
Because single precision IEEE754 floating point numbers only have 23 bits of precision (24 including the implicit 1 bit at the start).
That equates to roughly seven decimal digits and you can see that your number has eight digits in it.
All that's happening is that the computer is choosing the closest number to what you asked for that it can represent.
If you need more precision, use a double. That gives you 52/53 bits which equates to about 15 decimal digits.
After some testing, I got this result:
final float RF_FREQUENCY = 956.35625f;
System.out.println(String.format("%.5f", RF_FREQUENCY));
final BigDecimal xRF_FREQUENCY = new BigDecimal(956.35625);
System.out.println(String.format("%.5f", xRF_FREQUENCY));
And the output was:
956,35626
956,35625
So, as its explained in more details from coderanch and in this blog post, I recommend you to change to BigDecimal
.
EDIT: I've found another post about same problem in stackoverflow Double vs. BigDecimal? Hope it helps you.
Floats can't represent every number, so numbers are rounded. Doubles are the same, but with a higher precision. If you use Double your output will be 956.35625 (in this special case).