I need to write a method in java that converts a given string to float. my problem is how to avoid overflows - not to get value bigger than Float.MAX_VALUE AND lower than Float.MIN_VALUE;
tnx!
Clamp it to the range:
float clamped = Math.max(Float.MIN_VALUE, Math.min(Float.MAX_VALUE, Float.parseFloat(yourString)));
Note that you say "not ... lower than Float.MIN_VALUE" - this might not be quite what you intend: unlike Integer and Long's MIN_VALUE, which is large and negative, Float and Double's MIN_VALUE is a very small positive number.
If you mean that you want clamped to be positive, use max(Float.MIN_VALUE, ...) as above; if you mean that you don't want it to be negative and infinite, use max(-Float.MAX_VALUE, ...) instead.
If you need to validate that the value is in the range and throw an exception if not, write a method:
float checkRange(float v) {
if (Float.isNan(v)) throw new IllegalArgumentException("Too not numbery!");
if (v < Float.MIN_VALUE) throw new IllegalArgumentException("Too small!");
if (v > Float.MAX_VALUE) throw new IllegalArgumentException("Too big!");
return v;
}
min works if you give it a value less than Float.MAX_VALUE, and if you give it a value greater than Float.MAX_VALUE. (Same for max).