简体   繁体   中英

Python yaml output - float precision?

I'm using pyyaml to outputting yaml files from python dictionaries and am wondering how to set the precision or output format of the floats when they get written to files.

How do I create the yaml.dumper to handle this?

According to http://pyyaml.org/browser/pyyaml/trunk/lib/yaml/representer.py pyyaml uses the canonical string representation format of repr() when dumping floats. To be more precise, the main line of code that converts floats to strings is

# If data is a finite float and not nan
value = unicode(repr(data)).lower()

Looks like you'll have to do your own string conversion of floats if you want something different. You could either convert floats to strings ahead of time in your program or write your own Representer class to initialize yaml.dumper.Dumper with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM