Decimals
Steve Holden
steve at holdenweb.com
Tue Jun 13 12:45:49 EDT 2006
Tgone wrote:
> Sybren Stuvel wrote:
>
>>Tgone enlightened us with:
>>
>>>Sorry, when I print out the variable it displays as '15.0'. The
>>>price is '15.00' in the database though.
>>
>>That's the same thing, isn't it? 15.0 == 15.000000000
>
>
> Yes, they're both mathematically the same. I never said they weren't...
>
>
>>>Here's my code:
>>>
>>>product = Product.get(2)
>>>print product.price # 15.0
>>
>>Try string formatting:
>>
>>print '%.2f' % product.price
>
>
> That works. I expected Python to display the data exactly as it is in
> the database, like most languages.
>
Well I'm sorry Python doesn't live up to your expectations, but I think
your assertion "like most languages" is a little over-reaching.
What's actually happening is that the database is storing the number in
some internal format known to itself. The module you are using to access
the database is actually converting that value to a floating-point
number (I'm guessing here: some more modern modules will convert it to a
decimal). That's where the scaling factor gets lost, as until fairly
recently Python only *had* floats (well, and complex numbers)to
represent non-integral numbers.
So basically you are likely to be stuck with formatting the data the way
you want to see it. This is fairly usual in my experience.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Love me, love my blog http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list