Search code examples
pythonbotscryptocurrencybinance

How to round (or perhaps cut) of a float based on some conditions


I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error. I have tried to do it with the following code.but doesn’t work

import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `

Solution

  • You would be much better off working with decimal.Decimal and not with the language's native float type, which is prone to accuracy errors to begin with.

    I'd also bet that 0.0044859999999999995 btc is in fact given to you as a very big integer of smaller units (not sure about btc, but for eth those units are called wei).

    If that is indeed the case, then you should strive to keep it this way, and do all your math using integers only (i.e., not even Decimal, just plain integers and the // operation wherever needed).

    If you insist on doing it with non-integer values, then you could modify your code to this:

    from decimal import Decimal
    from decimal import getcontext
    from decimal import ROUND_DOWN
    
    getcontext().prec = 100
    getcontext().rounding = ROUND_DOWN
    
    num = Decimal('0.0044859999999999995')
    numCoins = Decimal(int(num*1000000))/1000000