Skip to content Skip to sidebar Skip to footer

How To Round Numeric Output From Yaml.dump, In Python?

Is there a clean way to control number rounding output of yaml.dump? For example, I have a class with different complexity variables, some of which are double precision numbers I w

Solution 1:

You could round it manually:

#!/usr/bin/env pythonimport yaml

deffloat_representer(dumper, value):
    text = '{0:.4f}'.format(value)
    return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
yaml.add_representer(float, float_representer)

print(yaml.safe_dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))
print(yaml.dump([1 / 11, 1 / 13, 1 / 17, 'some more text']))

Output

[0.09090909090909091, 0.07692307692307693, 0.058823529411764705, some more text]

[0.0909, 0.0769, 0.0588, some more text]

You might need to add more code for corner-cases, see represent_float() as @memoselyk suggested.

Solution 2:

Create your own repesenter for floats that formats the float numbers as you desire, and replace the existing representer with yaml.add_representer(float, my_custom_repesenter).

Here you can find the default representer for floats. You can take that code as an starting point and only change the path where value is not [+-].inf or .nan, and massage the value into your desired precision.

Post a Comment for "How To Round Numeric Output From Yaml.dump, In Python?"