Search code examples
javafloating-pointmaxlength

What is the largest possible length of a string-representation of a float?


Title pretty much says it all...

I am trying to enforce the maximum length of text input on a form. One of the fields can be any valid floating-point number. What would its maximum length be?

For example, for an integer

// negative sign makes MIN_VALUE larger than MAX_VALUE
String.valueOf(Integer.MIN_VALUE).length();

UPDATE

I have tested the following:

String.valueOf(-Float.MIN_VALUE).length();
String.valueOf(-Float.MAX_VALUE).length();
String.valueOf( Float.MIN_VALUE).length();
String.valueOf( Float.MAX_VALUE).length();

Which gives me the following output:

8
13
7
12

I'm not convinced that 13 is the maximum length


Solution

  • A maximum length for a float value doesn't make sense.

    If you want the user to enter any float value representable by java you want allow thing like

    1000000000000000000000000000000000000000000000000000000000000000
    

    or even

    000000000000000000000000000000000000000000000000000000000.00000000000000000000001
    

    Limits for input fields should be based on business needs not on rules like "I have a limit on all other fields".

    The "business" rule here so far seems to be "Can be parsed and stored into a float"

    Also note that limiting the input length often prevents input (via cut&paste) of stuff that is longer and only becomes valid input after some editing. So it actually reduces usability.