David Saltares
David Saltares

Reputation: 838

Turn -0.00 into 0.00 float in Python

I'm parsing an XML file with some coordinates in Python to write a transformed output file. The problem is that some coordinates are -0.00 and I'm having some problems parsing them in another system. I would need them to be 0.00 instead of -0.00. How could I achieve such thing?

This is what I'm doing so far:

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']))

Upvotes: 2

Views: 390

Answers (4)

NPE
NPE

Reputation: 500713

You can use the fact that the negative zero compares equal to the positive zero:

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

This turns -0. to 0., and leaves every other number intact.

Upvotes: 0

John Machin
John Machin

Reputation: 82992

You don't need 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]

Upvotes: 2

Raymond Hettinger
Raymond Hettinger

Reputation: 226524

If the value is equal to zero (either positive or negative), take the absolute value:

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

Upvotes: 4

Drathier
Drathier

Reputation: 14539

Maybe you could split the string before parsing it as a number? Just remove the "-" from the input.

Upvotes: 0

Related Questions