python - Format value to float with width and precision -


i validate string input verify if formated valid float given width , precision.

width = 10 precision = 4  value = '12'  try:    "{10.4f}".format(value) except:    print "not valid" 

this test fails should works because 12 considered float 12.0000

i have dynamic test because width , precision variables.

thank help!

you forgot : colon:

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

otherwise python interprets first digit positional parameter index.

each parameter can set it's own placeholder:

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

width , precision arguments interpolated before value formatted.

this is, however, not test floating point inputs. float value 12.234 cannot represented; binary fractions can approximate it:

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

so value wouldn't 'fit' 10.4 constraints, yet when rounded valid input give.

any floating point value can formatted fixed width, in case:

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

no valueerror raised; 10 in width parameter means: produce string @ least many characters wide, pad spaces if shorter, , width includes decimal point , decimals.

to validate floating point input, best can test can converted float, , test mininum , maxmimum values:

try:     value = float(value) except valueerror:     # cannot converted valid float     return "not valid input" else:     if 0 <= value < 10 ** 11:         return "value out of range" 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -