在Python中将-0.00转换为0.00浮点数

时间:2011-10-22 23:32:49

标签: python xml file floating-point

我正在使用Python中的一些坐标解析XML文件以编写转换后的输出文件。问题是有些坐标是-0.00,我在另一个系统中解析它们时遇到了一些问题。我需要它们是0.00而不是-0.00。我怎么能实现这样的呢?

这就是我到目前为止所做的事情:

for node in nodes:
    nodeName = node.attrib['name']
    nodeParts = nodeName.split('.')
    nodeName = nodeParts[0]

    if nodeName == 'scene':
        f.write(nodeParts[1] + '\t')

        position = node.find('position')
        f.write('%.2f ' % float(position.attrib['x']))
        f.write('%.2f ' % float(position.attrib['y']))
        f.write('%.2f\n' % float(position.attrib['z']))

4 个答案:

答案 0 :(得分:4)

如果该值等于零(正数或负数),则取绝对值:

>>> x = float('-0.0')
>>> x
-0.0
>>> abs(x)
0.0

答案 1 :(得分:2)

您不需要abs()

>>> test_values = [-1.0, -0.0, 0.0, 1.0]
>>> test_values
[-1.0, -0.0, 0.0, 1.0]
>>> [x if x else 0.0 for x in test_values]
[-1.0, 0.0, 0.0, 1.0]
>>> [x or 0.0 for x in test_values]
[-1.0, 0.0, 0.0, 1.0]
>>> [x + 0.0 for x in test_values]
[-1.0, 0.0, 0.0, 1.0]

答案 2 :(得分:0)

也许你可以在将字符串解析为数字之前拆分它?只需从输入中删除“ - ”即可。

答案 3 :(得分:0)

您可以使用负零比较等于正零的事实:

def f(x):
   return 0. if x == 0. else x

这会将-0.变为0.,并保留其他所有数字。

相关问题