Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.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_Csv_Formatting - Fatal编程技术网

python将数字转换为美元格式

python将数字转换为美元格式,python,csv,formatting,Python,Csv,Formatting,我正在导入一个csv文件,其中一个价格缺少零 期望输出:12.10 电流输出:12.1 如何强制数据中包含零 到目前为止我所做的: #!/usr/bin/python import csv import sys import argparse #parsing command line options parser = argparse.ArgumentParser(prog='desc', description=__doc__) parser.add_argument('-i', '--

我正在导入一个csv文件,其中一个价格缺少零

期望输出:12.10

电流输出:12.1

如何强制数据中包含零

到目前为止我所做的:

#!/usr/bin/python

import csv
import sys
import argparse

#parsing command line options
parser = argparse.ArgumentParser(prog='desc', description=__doc__)
parser.add_argument('-i', '--input', help='Input file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument('-o', '--output', help='Output file', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
args = parser.parse_args(sys.argv[1:])
inf, outf = args.input, args.output
outf = csv.writer(outf)

print 'Loading %s file into memory' % inf.name
data = []
tmp = 0.00
for i, line in enumerate(csv.reader(inf)):
    if i == 0:
        outf.writerow(line)
        continue
    price = line[4]
    price = price.replace('.', '')
    # print price
    if (price < 100):
        tmp = price
        tmp = tmp * 10
        print tmp
两种选择:

使用小数位数重要的类型,例如

暂时忽略它,并在输出时使用指定两位小数的格式,如%.2f

您的浮点值是一个带2位小数的字符串:

>>> '{:.2f}'.format(12.1)
'12.10'
PS:您不需要使用重载枚举函数跳过csv文件的头并在输出中重写它。您可以直接写第一行:

csvin = csv.reader(inf)
outf.writerow(csvin.next())  # header line 1
for line in csvin:  # iterator goes on from line 2
    price = line[4]
    #...
而不是

print tmp
试一试


这将强制浮点格式设置为两位小数。

这将导致以下错误:ValueError:类型为'str'的对象的未知格式代码'f',如果price<100:您试图将字符串与int对象进行比较?首先将其转换为float或int,这就是为什么会出现错误。是否可以将该变量保存为小数点后两位?每次我在像libreoffice这样的csv程序中打开它时,最后一个0都会消失。如果你用Excel或libreoffice打开csv生成的文件,它们会解释你的文件,电子表格中的尾随零也会消失。如果要保留尾随零,则应直接生成excel文件或odf文档
>>> price=12.10
>>> price
12.1
>>> print('{0:.2f}'.format(price))
12.10
>>> price=12.10
>>> price
12.1
>>> print('{0:.2f}'.format(price))
12.10