Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format value to float with width and precision

I would like to validate a string input to verify if it could be formated to a valid float for given width and precision.

width = 10
precision = 4

value = '12'

try:
   "{10.4f}".format(value)
except:
   print "not valid"

this test fails but it should works because 12 could be considered as a float 12.0000

I would also like to have a dynamic test because width and precision are variables.

Thank you for your help!

like image 921
Below the Radar Avatar asked Dec 10 '25 09:12

Below the Radar


1 Answers

You forgot the : colon:

"{:10.4f}".format(float(value))

otherwise Python interprets the first digit as a positional parameter index.

Each parameter can be set with it's own placeholder:

"{value:{width}.{precision}f}".format(
    value=float(value), width=width, precision=precision)

width and precision arguments are interpolated before the value is formatted.

This is, however, not a good test for floating point inputs. The float value 12.234 cannot be exactly represented; binary fractions can only approximate it:

>>> format(12.234, '.53f')
'12.23399999999999998578914528479799628257751464843750000'

so this value wouldn't 'fit' your 10.4 constraints, yet look when rounded like a perfectly valid input to give.

Any floating point value can be formatted to a fixed width, in any case:

>>> format(10**11 + 0.1, '10.4f')
'100000000000.1000'

No ValueError will be raised; the 10 in the width parameter means: produce a string that is at least this many characters wide, pad with spaces if it is shorter, and this width includes the decimal point and the decimals.

To validate floating point input, the best you can do is test that it can be converted to a float, and then test for mininum and maxmimum values:

try:
    value = float(value)
except ValueError:
    # cannot be converted to a valid float
    return "Not a valid input"
else:
    if 0 <= value < 10 ** 11:
        return "Value out of range"
like image 76
Martijn Pieters Avatar answered Dec 11 '25 21:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!