I have a series of floating point numbers that I need to print out in a specific format, very similar to scientific notation. Given the number -345.678, scientific notation would give me -3.45678E2 but instead I need to output -.345678D03. Specifically, I cannot have any digits to the left of the decimal point. Is there any way to do this in Python 3?
1 Answers
0
votes
I'm not sure of the full details of your format, but the following should either work or be easily modifiable to work:
from decimal import Decimal
def sci_str(dec):
return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)
def mod_sci_str(x):
s = sci_str(10*Decimal(str(x)))
s = s.replace('E+','D0')
s = s.replace('E-','D0-')
s = s.replace('.','')
if s.startswith('-'):
return '-.' + s[1:]
else:
return '.' + s
The function sci_str is a clever utility due to @MikeM in this question
For example:
>>> mod_sci_str(-345.678)
'-.345678D03'
>>> mod_sci_str(345.678)
'.345678D03'
>>> mod_sci_str(0.0034)
'.34D0-2'