I have a line in my code much like below:
float rand = (float) Math.random();
Math.random() returns a double that is >=0.0
and <1.0
. Unfortunately, the cast above may set rand
to 1.0f
if the double is too close to 1.0
.
Is there a way to cast a double to a float in such a way that when no exact equal value can be found, it always rounds down to the next float value instead of to the nearest float value?
I'm not looking for advice on RNGs, nor work-arounds such as following up with if(rand == 1.0f) rand = 0.0f;
. In my case, that solution is a satisfactory way to fix my problem, and it has already been implemented. I am just interest in finding out "proper" solution to this kind of number conversion.
If you only want to round when rand==1.0f
, then I second @paxdiablo's answer. However, it sounds like you're okay with always rounding, and simply want to always round down. If so:
float rand = Math.nextDown((float)Math.random());
from the javadoc:
nextDown(float f) Returns the floating-point value adjacent to f in the direction of negative infinity.
In response to your comment - good point. To avoid that problem, you could simply wrap the statement in a call to Math.abs()
, which will have no affect except when the result of nextDown()
is negative.
float rand = Math.abs(Math.nextDown((float)Math.random()));