Saturday 31 December 2016

python - How do I limit an output's maximum number of characters?




I'm trying to limit a number's output to 4 characters (including decimals).



def costEdit(nCost):
nCost = '%.2f'%(nCost*1.25)
nCost = nCost * 1.25
return nCost


I want the nCost to be cut off at 2 decimal places. E.g. if the nCost was 8.364912734, cut it off to 8.36 and edit the nCost variable to be replaced with that. Any Ideas?




Im getting the error:



Traceback (most recent call last):
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 59, in
costEdit(nCost)
File "C:\Python33\My Codes\TextTowns\TextTowns.py", line 27, in costEdit
nCost = nCost*1.25
TypeError: can't multiply sequence by non-int of type 'float'



Im using it as: costEdit(nCost)


Answer



The problem you're having is confusion between a number, and a string representation of a number. These are different things.



When you do this:



nCost = '%.2f'%(nCost*1.25)



… you're multiplying your number by 1.25, then replacing it with a string that represents the number up to two decimal points. So, when you do this:



    nCost = nCost * 1.25


… you're trying to multiply a string by 1.25, which makes no sense.






I suspect you didn't want a string here at all; you just wanted to round the number as a number. To do that, use the round function:




nCost = round(nCost*1.25, 2)





Of course as soon as you multiply by 1.25 again, you may "unround" it by another decimal place or two:



>>> nCost = 1.33333
>>> nCost = round(nCost*1.25, 2)

>>> nCost
1.33
>>> nCost = nCost * 1.25
>>> nCost
1.6625


And really, it's almost always a bad idea to round values before doing arithmetic on them; that just multiplies rounding errors unnecessarily. It's better to just keep the highest-precision value around as long as possible, and round at the last possible second—ideally by using %.2f/{:.2f} formatting in the printing/writing-to-disk/etc. stage.







Another thing to keep in mind is that not all real numbers can be represented exactly as floats. So, for example, round(13.4999, 2) is actually 13.949999999999999289457264. A simple repr or str or %f will print this out as 13.95, so you may not notice… but it's still not exactly 13.95.



The best way to solve this problem, and your other problems, is to use the Decimal type instead of the float type. Then you can round the value to exactly 2 decimal places, do math in a 2-decimal-places context, etc.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...