如何将数字格式化为 NN.nn 样式

How to format a number into NN.nn style

我正在处理来自传感器的数字流,并希望将它们格式化为以小数点为中心的 'standard' 布局,如下所示:1.00 = 01.00 | 12.9 = 12.90 | 2 = 02.00 | 49.09 = 49.09 等等

我已经尝试过 zfill 和 round - 包括组合,但小数点在我迄今为止尝试过的所有内容中移动。目的是填充预定义的字段以供以后分析。

更新 可能不是最优雅的解决方案,但我想出了这个,到目前为止我已经能够测试它有效:

对于小数点左边的填充:

def zfl(d, chrs, pad):
 # Pads the provided string with leading 'pad's to suit the specified 
 # 'chrs' length.
 # When called, parameters are : d = string, chrs = required length of 
 # string and pad = fill characters
 # The formatted string of correct length and added pad characters is 
 # returned as string
 frmtd_str = str(d)
 while len(frmtd_str) != chrs:
     # less then required characters
     frmtd_str = pad + frmtd_str
 return(frmtd_str)`

小数点右边补齐函数:

def zfr(d, chrs, pad):
# Pads the provided string with trailing 'pad's to suit the specified 
# 'chrs' length
# When called, parameters are : d = string, chrs = required length of 
# string and pad = fill characters
# The formatted string of correct length and added pad characters is 
# returned as string
frmtd_str = str(d)
while len(frmtd_str) != chrs:
    # less then required characters
    frmtd_str = frmtd_str + pad
return(frmtd_str)

调用上述函数的示例:

原始数据以小数点为分隔符分为两部分:

dat_splt = str(Dat[0]).split(".",2)

然后padding进行重构使用:

exampledat = "{}.{}".format(zfl(dat_splt[0],3,'0'), zfr(dat_splt[1],3,'0 '))

备注:

  1. 填充任一侧需要字符串参数、所需字符和 'pad' 字符。
  2. 需要的字符可以是任何字符(只测试了1到10)
  3. 最终返回的字符串可以是不对称的,即 nnnnn.nn 或 n.nnn
  4. 容纳原始数据各部分的字符数

对此结果非常满意,它可以作为常用函数重用。我确信还有更多 'economical/efficient' 方法,但我还没有找到这些方法,但至少这个方法有效,提供了有序且稳定的文本字符串结果列表(这正是我此时的目标)。

希望我的布局正确..:-)

'{:0>5.2f}'.format(n)

'{:0>5.2f}'.format(1)
'01.00'
'{:0>5.2f}'.format(12.9)
'12.90'
'{:0>5.2f}'.format(49.09)
'49.09'

https://queirozf.com/entries/python-number-formatting-examples#left-padding-with-zeros