Rounding a number

Dave Angel davea at davea.name
Thu Apr 30 18:58:50 EDT 2015


On 04/30/2015 06:35 PM, Seymore4Head wrote:
> On Thu, 30 Apr 2015 22:00:17 +0200, Thijs Engels
> <thijs at buckazoids.com> wrote:
>
>> round(65253, -3)
>>
>> might be what you are looking for...
>>
>>
>> On Thu, Apr 30, 2015, at 21:49, Seymore4Head wrote:
>>> I have this page book marked.
>>> https://mkaz.com/2012/10/10/python-string-format/
>>>
>>> I am getting numbers from sixty thousand to two hundred thousand.
>>> I would like to round them to the nearest thousand.
>>> So 65,253 should read 65,000.
>>> How?
>>>
>>> Total=2100
>>> for x in range (10,35):
>>>      count=1000/x
>>>      print ("Foo {:7,.0f} Fighters".format(Total*count))
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>
> Thanks
>
> I know there are more than one way to round and answer.  I was hoping
> that using the {:7,.0f} formatting had a solution.
>

There are definite tradeoffs, but since you're rounding to integer size, 
the round() function works fine.  If you wanted tenths, you'd have to 
realize that a float (which is binary float) can't represent them 
exactly.  So depending on what further processing you do, you might see 
some effects that would not seem like it worked right.

Using the % or the .format style of formatting works fine, but it gives 
you a string.  You didn't specify that, so people probably assumed you 
wanted numbers.

-- 
DaveA



More information about the Python-list mailing list