1

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!

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

tnx! can you please provide me an explanation?
Just think about 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).
But it may give wrong value(answer) when overflow occurred.
so what is the solutin for this? @Md.KawserHabib
@Md.KawserHabib can you give an example?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.