Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting numerical value from Python Decimal

Tags:

python

decimal

When I use the python Decimal object simply with something like:

from decimal import *
dec = Decimal('3.432')
print dec

it will print 3.432, just like I want, but if i try to put that same value dec into a json object what I get in the json is Decimal("3.432"). How can I just get the numerical value from decimal?

like image 479
whatWhat Avatar asked Feb 16 '10 00:02

whatWhat


People also ask

How do you extract the decimal part of a number in Python?

Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you find the numbers after a decimal point?

The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left.


1 Answers

>>> str(decimal.Decimal('3.1'))
'3.1'

Out-of-the-box JSON uses a few primitive types, like strings, heavily.

Your best bet is to convert your Decimals to strings when creating your JSON document from some Python object.

Convert the strings back to Decimal when converting the JSON document back to a Python object.

like image 146
S.Lott Avatar answered Oct 20 '22 19:10

S.Lott