I need help understanding whats going on in the function, especially the return statements. I know what the return statements do but not how they do it. I know that they format the string but I just don’t understand how its being done. It would help if you guys take it step by step.
def intF(n, d, l=40):
s=str(n*10**l / d)
if len(s) < l:
return '0.{:0>{width}}'.format(s,width=l)
if len(s) > l:
return s[0:len(s)-l]+'.'+s[len(s)-l:]
return '0.'+s
Here’s a line-by-line breakdown:
Pretty obvious.
nis a number,dis another number (the divisor) andlis the number of digits to print after the decimal point.This does something a bit unusual. Rather than relying on floating point arithmetic, this multiplies
nby10 ** l, i.e. by a1followed byldigits. That way the final result won’t have any floating point error — assumingdis always an integer. (But of course any remaining digits get truncated. Also, replace/with//in Python 3 to get the same behavior.)At this point,
swill be a string representation of a whole number — again assumingdis an integer — but it will have the same digits as the result offloat(n) / d. So now we just have to insert the decimal point in the right place.If the length of
sis less thanl, then we need to pad it and prepend a0.. That’s what this does. The{:0>{width}}field says to create a zero-padded field ofwidthwidth, and insert a value into it on the right (>) side. Thensis passed in viaformat, and we have our result.If the length of
ais greater thanl, then we need to insert the decimal point in the correct spot. That’s what this does. It removes the trailingldigits froms, appends a., and then appends the remainingldigits.The final possibility is that
sis exactlyldigits long. In that case, we don’t need to do any padding; we can just prepend a0and a decimal point.As a final note: if you pass anything but integers to this function, it will not work as expected. Consider this:
Or this: