What is the best way to store fixed point decimal values ​​in Python for cryptocurrency?

I play with the development of a Django / Python application that stores and performs calculations on cryptocurrency values. These are decimal values ​​up to 8 decimal places, for example, 0.00000008, 4.10500008, 6000.00000000.

Perhaps, partly because you are not completely sure about the nuances of Python Decimal, and partly on the tips that I saw for different languages, I thought it would be safer to store values ​​as their equico values ​​for satoshi in the BigInteger field For example, for 0.00000008 I stored 8, for 4.10500008 I stored 410500008 and for 6000.00000000 I store 600000000000.

Is this a good idea or should I use Decimal with a specific setting?

Thank!

+4
source share
1 answer

You can safely use Decimal. It is really decimal under the hood, i.e. No database conversion errors. If you store

import decimal

d = decimal.Decimal('4.10500008')

there will be no loss of accuracy.

Just make sure you create numbers using strings, because otherwise you will have problems:

>>> decimal.Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')

against

>>> decimal.Decimal('1.1')
Decimal('1.1')

Another important thing to understand is that it decimal.Decimalalso carries accuracy:

>>> decimal.Decimal('1.10')
Decimal('1.10')

This is very useful when using financial applications.

For more info see https://docs.python.org/2/library/decimal.html

N.B.. Mark Dickinson , decimal , . decimal.getcontext().prec, - 28. ( ), , .

+4

Source: https://habr.com/ru/post/1548279/


All Articles