Hmm. You changed the original question; the way it is now it should be trivial: since you're checking for whether float()
works now, just be consistent with that: stop using int()
! That is, change to this:
def format_decimal(value, decimals):
try:
if decimals == 2:
value = float(value)/100
return "{:.2f}".format(value)
except ValueError:
raise
But the code is still confused:
- Why are you dividing by 100? Do you really want, e.g.,
"1234"
to change into "12.34"
?
- What if
decimals
isn't 2? Then your format_decimal()
does nothing: it "falls off the end" and so returns None
.
- Catching an exception and immediately re-raising it is the same as not bothering to catch it to begin with. That is, the
try/except
structure, as written, does nothing except complicate the code.
It would really help if you gave exact examples of input strings and their expected output strings.
Generalizing
Try this?
def format_decimal(value, decimals=2):
from decimal import Decimal
# divide value by 10**decimals; this is just scaling
value = Decimal(value).scaleb(-decimals)
return "{:.{d}f}".format(value, d=decimals)
That allows specifying the scaling factor (decimals
). Here's sample input/output. If anything isn't what you want, say exactly what it is that you do want:
for v in "1", "1234.5678", "1.2e6":
for d in range(4):
print repr(v), d, "->", repr(format_decimal(v, d))
and the output:
'1' 0 -> '1'
'1' 1 -> '0.1'
'1' 2 -> '0.01'
'1' 3 -> '0.001'
'1234.5678' 0 -> '1235'
'1234.5678' 1 -> '123.5'
'1234.5678' 2 -> '12.35'
'1234.5678' 3 -> '1.235'
'1.2e6' 0 -> '1200000'
'1.2e6' 1 -> '120000.0'
'1.2e6' 2 -> '12000.00'
'1.2e6' 3 -> '1200.000'