Mark Lawrence | 1 Jul 18:25 2010
Picon

Re: puzzled by Python 3's print()

On 01/07/2010 14:11, Richard D. Moores wrote:
> On Thu, Jul 1, 2010 at 04:57, Steven D'Aprano<steve <at> pearwood.info>  wrote:
>> On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
>>>>>> x = 2000000000000034
>>>>>> x/2
>>> 1000000000000017.0
>>>
>>>>>> print(x/2)
>>> 1e+15
>>>
>>> I was expecting, in fact needing, 1000000000000000017 or
>>> 1000000000000000017.0
>>>
>>> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>>
>> This is not an issue with print, this is an issue with floats -- they
>> produced a rounded, approximate value when converted to a string. print
>> merely prints that string:
>>
>>>>> x = 1e15 +17
>>>>> x
>> 1000000000000017.0
>>>>> print(x)
>> 1e+15
>>>>> str(x)
>> '1e+15'
>>
>>
>> If you want more control over the string conversion, you can do
>> something like this:
>>
>>>>> print(repr(x))
>> 1000000000000017.0
>>>>> print('%.5f' % x)
>> 1000000000000017.00000
>
> Thanks to yours and others responses, I've learned some things I
> didn't know, but remember, I'm starting with long ints such as
> x = 2000000000000034, cutting it in half, and hoping to print
> 1000000000000017 or 1000000000000017.0
> (I also need to divide odd ints like 2000000000000033 and print
> 1000000000000017.5)
>
> (In my initial post, I used a smaller x, x = 2000000000000034.  I
> should have made it longer, to reflect the ints I'm dealing with (big
> primes and their near neighbors).
>
> I'm still hoping to be saved from the decimal module :)  .

I think that we can manage that. :)

>
> Dick
> _______________________________________________
> Tutor maillist  -  Tutor <at> python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Take a look at section 7.1.3 here.

http://docs.python.org/py3k/library/string.html#string-formatting

This is the recommended way to format strings in Python 3.

Kindest regards.

Mark Lawrence.

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Gmane