简体   繁体   中英

Strict Python formatting for floats

I'm using PYTHON to write to a file where the formatting is very strict. I have 10 available spaces in each column which cannot be exceeded.

I want to write the as many decimals as I can, but if the number is negative, the minus sign must be preferred over the last decimals. Also the period in the float must be counted into the number of available spaces. Numbers should be right trunctated

Example: Let's say I want to print two numbers

a = 123.4567891011
b = 0.9876543210

Then I would want the result:

123.4567890.98765432

But if I now have the following:

a = -123.1111111111 
b = 98765.432101234
c = 567
d = 0.1234

Then I'd want:

-123.1111198765.4321     567.0    0.1234

Would be to nice use exponential notation for high numbers, but not a necessity. I'm unable to find the answer. All I can find is to fix the format to number of significant digits, which really won't help me.

I've tried several methods of the

f.write({0:>10}{1:>10}.format(a,b))

but can't figure it out. Hope you see what I`m looking for.

Okay, so I found a way. I basically convert everything to strings and use:

f.write("{0:>10.10}{1:>10.10}".format(str(a),str(b)))

and so on..

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