Issue while writing values from ghpython to csv

Hello!

I am trying to write point coordinates, more specifically the xcoordinate value and the y coordinate value to a CSV file from GHpython.

I am rounding the coordinate values by 2 decimals and then writing them to separate columns, but on opening the file some values have not taken the decimal correction. I do not understand why this happens. my code is attached below and an image of the CSV file output. Any suggestion would be very helpful! thanks in advance

import Rhino as rc
import Rhino.Geometry as rg
import rhinoscriptsyntax as rs


fileName = open(fileAddress, 'w')
for pt in points: 
    
    a = round(pt.X,2)
    b = round(pt.Y,2)

    fileName.write(`a` + ';' + `b`+ '\n')
    
fileName.close()

Call str on a and b instead, or you could even take care of the rounding too with a formatting string to handle the conversion.

    fileName.write(`a` + ';' + `b`+ '\n')

On this line the backticks are calling repr on a and b. This causes some non-integer values with repeating binary expansions (the binary equivalent of 1/3 = 0.33333…), to have a floating point precision issue (https://0.30000000000000004.com/). In GHPython or IronPython just try:

print(`4.55`)

It’s a known isssue in Iron Python repr for floats is inconsistent with CPython · Issue #102 · IronLanguages/ironpython2 · GitHub (in which it even effects decimal.Decimals!). But backtick repr was still one of the first things to be deprecated in Python 3, so ought to be avoided.

Thanks for explaining James ! :slight_smile:

1 Like