@Harvey251, , .
:
import formatfloat
width = 8
ff8 = formatfloat.FormatFloat(width)
print(ff8(12345678901234))
. formatfloat.py , FlotFormat. , init FormatFlot.
import unittest
class FormatFloat:
def __init__(self, width = 8):
self.width = width
self.maxnum = int('9'*(width - 1))
self.minnum = -int('9'*(width - 2))
def __call__(self, x):
if x > self.minnum and x < self.maxnum:
o = f'{x:{self.width - 1}}'
if '.' not in o:
o += '.'
elif len(o) > self.width:
o = str(round(x, self.width-1 - str(x).index('.')))
else:
for n in range(max(self.width, 5) - 5, 0, -1):
fill = f'.{n}e'
o = f'{x:{fill}}'.replace('+0', '+')
if len(o) == self.width:
break
else:
raise ValueError(f"Number is too large to fit in {self.width} characters", x)
return o
class TestFormatFloat(unittest.TestCase):
def test_all(self):
test = (
("1234567.", 1234567),
("-123456.", -123456),
("1.23e+13", 12345678901234),
("123.4567", 123.4567),
("123.4568", 123.45678),
("1.234568", 1.2345678),
("0.123457", 0.12345678),
(" 1234.", 1234),
("1.235e+7", 12345678),
("-1.23e+6", -1234567),
)
width = 8
ff8 = FormatFloat(width)
for expected, given in test:
output = ff8(given)
self.assertEqual(len(output), width, msg=output)
self.assertEqual(output, expected, msg=given)
if __name__ == '__main__':
unittest.main()
source
share