Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以特定方式格式化浮动?_Python_Python 3.x - Fatal编程技术网

Python 如何以特定方式格式化浮动?

Python 如何以特定方式格式化浮动?,python,python-3.x,Python,Python 3.x,我有两个浮点数作为python代码的结果 30.00 3995.0081 我希望以这样一种方式对它们进行格式化:它们的总位数相等(示例11)。例如,上述两位数字将产生以下结果 30.000000000 3995.0081000 如果您注意到,这两个数字中小数点后的数字是不相等的,但总数字是相同的。 我试着用下面的方法 print('{0:11.9f}'.format(number)) 但它会产生以下错误的结果 30.000000000 3995.008100000 是否有任何方法或功能

我有两个浮点数作为python代码的结果

30.00 
3995.0081
我希望以这样一种方式对它们进行格式化:它们的总位数相等(示例11)。例如,上述两位数字将产生以下结果

30.000000000
3995.0081000
如果您注意到,这两个数字中小数点后的数字是不相等的,但总数字是相同的。 我试着用下面的方法

print('{0:11.9f}'.format(number))
但它会产生以下错误的结果

30.000000000
3995.008100000
是否有任何方法或功能可以产生所需的结果?

十进制('0.142857')

十进制(“0.1428571428571428571428571428571429”)


我假设这只是为了显示的目的,所以字符串允许这样做。您给出的两个数据示例中都包含小数,但我不知道是否总是这样。如果不是的话,会有一点额外的逻辑;但我认为这会让事情开始

def sizer(input_number):
    output = str(float(input_number)) + '0' * 11  # or some number in excess of the desired number of digits 
    output = output[0:12]  # based on the example of 11 desired digits
    print(output)

sizer(30.00)
sizer(3995.0081)

您可以定义一个自定义打印函数来调整格式化字符串:

def custom_print(n, ndig=11):
    spec = '{0}.{1}f'.format(ndig, ndig -1 - len(str(n).split('.')[0]))
    print(n.__format__(spec))

custom_print(a)
custom_print(b)

>>>30.00000000
>>>3995.008100
其中
ndig-1-len(str(n).split('.)[0]
是小数点后的位数。

回答得不错。使用
str(float(input_number))
还可以涵盖参数为
int的情况。
def sizer(input_number):
    output = str(float(input_number)) + '0' * 11  # or some number in excess of the desired number of digits 
    output = output[0:12]  # based on the example of 11 desired digits
    print(output)

sizer(30.00)
sizer(3995.0081)
def custom_print(n, ndig=11):
    spec = '{0}.{1}f'.format(ndig, ndig -1 - len(str(n).split('.')[0]))
    print(n.__format__(spec))

custom_print(a)
custom_print(b)

>>>30.00000000
>>>3995.008100