简体   繁体   English

格式化值以浮动和宽度和精度浮动

[英]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 这个测试失败但它应该有效,因为12可以被认为是浮点数12.0000

I would also like to have a dynamic test because width and precision are variables. 我还想进行动态测试,因为宽度和精度是变量。

Thank you for your help! 谢谢您的帮助!

You forgot the : colon: 你忘记了:冒号:

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

otherwise Python interprets the first digit as a positional parameter index. 否则Python将第一个数字解释为位置参数索引。

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. 在格式化value之前插入widthprecision参数。

This is, however, not a good test for floating point inputs. 然而,这对于浮点输入来说不是一个好的测试。 The float value 12.234 cannot be exactly represented; 浮点值12.234无法准确表示; 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. 所以这个值不会“适合”你的10.4约束,但看起来像一个完全有效的输入舍入。

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; 不会引发ValueError ; 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. width参数中的10表示: 生成一个至少包含多个字符宽的字符串,如果它更短则填充空格 ,并且此宽度包括小数点和小数。

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: 要验证浮点输入,您可以做的最好的事情是测试它是否可以转换为float,然后测试mininum和maxmimum值:

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"

Let's use Python 3 我们来使用Python 3

Format Specifier f"{var}" 格式说明符 f"{var}"

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

There is a type mismatch here I think ... 我觉得这里有类型不匹配......

value = 12

not

value = '12'

First, instead of 首先,而不是

"{10.4f}".format(value)

write it as: "{10.4f}".format(float(value)) 把它写成:“{10.4f}”。format(float(value))

to convert to string to float first 首先转换为字符串浮动

On how to generalize this: instead of having the string "{10.4f}" hard-coded, create it 关于如何概括:不要将字符串“{10.4f}”硬编码,而是创建它

width = 10
precision = 4
formatting_string = '{' + str(width) + '.' + str(precision) + 'f}'

The, use 使用

formatting_string.format(float(value))

Using string rjust and ljust: 使用字符串rjust和ljust:

value.rjust(width)+'.'.ljust(precision+1,'0')+'f'

Output: 输出:

        12.0000f

In this way, we donot need to convert the value to float 这样,我们就不需要将value转换为float

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中格式化由宽度而不是精度分隔的浮点数? - How can I format a float in Python delimited by width, not by precision? 如何更改浮点值的格式(达到特定精度)并保持浮动? - How to change format of float value(up to particular precision) and keep it float? python 浮点格式,精度基于浮点值 - python float format with variable precision based on float value 如何将浮点数格式化为可变精度? - How can I format a float to variable precision? 如何格式化具有给定精度和零填充的浮点数? - How can I format a float with given precision and zero padding? 如何格式化 pandas dataframe 并保持原始浮点精度值 - How to format a pandas dataframe and keep original float precision values 将浮点数转换为位置格式的字符串(没有科学记数法和错误精度) - Convert float to string in positional format (without scientific notation and false precision) 熊猫to_csv浮点格式,任意精度,无需工程格式 - pandas to_csv float format arbitrary precision without engineering formating Python:如果需要,将浮点数格式化为最小浮点精度 - Python: format float to a minimum floating point precision if needed Python float精度浮点数 - Python float precision float
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM