Reputation: 5157
How can I format a float number to string, by using a mask?
(I'm not proficient in regex, but if someone knows an one-line solution, why not?)
Here is my problem:
I have a float number like "6.88" and I need to format it using the following mask "00000000000.00"
6.88 = "00000000006.88"
14.3 = "00000000014.30"
00.0 = "00000000000.00"
I've already read the following post but I couldn't understood it:
Format number number with specific mask regex python
Example of my data:
6.88 => 00000000006.88
56.62 => 00000000056.62
9.58 => 00000000009.58
24.75 => 00000000024.75
14.30 => 00000000014.30
My not so efficient nor fast solution:
Is there an easier way to do this?
Upvotes: 1
Views: 2257
Reputation: 41137
Another example based on string formatting (not very nice or error prone):
def format_float(string_format, number):
_int, _frac = string_format.split(".")
real_format = "%%%s%d.%df" % ("0", len(_int) + len(_frac) + 1, len(_frac))
return real_format % number
print format_float("00000.000", 1.2)
would yield: 00001.200
Upvotes: -1
Reputation: 46563
You'd use string formatting:
In [21]: '{:014.2f}'.format(6.88)
Out[21]: '00000000006.88'
In [22]: '{:014.2f}'.format(14.30)
Out[22]: '00000000014.30'
In [23]: '{:014.2f}'.format(0)
Out[23]: '00000000000.00'
According to 6.1.3.1. Format Specification Mini-Language,
0
is the fill character
.2
sets the precision to 2
14 is the width of the result string
Upvotes: 5