Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettier floats using yaml

Whenever I use yaml dump to dump floats, they start to look ugly.

Input:

a.yaml

a: 0.000000015

When I read it in and then dump it to file again, it will look like:

dumped.yaml

a: 1.5e-08

Note that there's no fixed size I can go for, i.e. maybe someone wants to put a lot of zeros (and I am not "afraid" of e.g. a small fraction with 20 leading zeros)

Also, if you choose a fixed size, then it might look like the following (which I am trying to avoid as well)

a: 0.0000000150000
like image 767
PascalVKooten Avatar asked Apr 22 '26 19:04

PascalVKooten


1 Answers

I haven't been able to find, in the format specification mini-language documentation, a way to format numbers the way you want them.

I propose a simple hack: to replace, in the output of PyYAML, all numbers in scientific notation with their fixed-point equivalent, like this:

import re
import yaml

# only accepts Python's/PyYAML's default scientific format, on purpose:
E_REGEX = re.compile(r'(\b|-)([1-9])(?:\.(\d+))?e([+-])(\d+)\b')

def e_to_f(match):
    sf, f0, f1, se, e = match.groups()
    if f1 is None: f1 = ''
    f = f0 + f1
    n = int(e)
    if se == '-':
        z = n - 1  # i.e., n - len(f0)
        if z < 0:
            return sf + f[:-z] + '.' + f[-z:]
        else:
            return sf + '0.' + '0' * z + f
    else:
        z = n - len(f1)
        if z < 0:
            return sf + f[:z] + '.' + f[z:]
        else:
            return sf + f + '0' * z + '.0'

e_dict = {
    'example': 1.5e-15,
    'another': -3.14e+16
}
e_txt = yaml.dump(e_dict, sort_keys=False)
f_txt = E_REGEX.sub(e_to_f, e_txt)
print(e_txt)
print(f_txt)

# output:
#
# example: 1.5e-15
# another: -3.14e+16
#
# example: 0.0000000000000015
# another: -31400000000000000.0

like image 186
Walter Tross Avatar answered Apr 24 '26 07:04

Walter Tross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!