3

I have following function, I'm trying to put a rate which is supposed to be a fractional number e.g. 0.5, 1.5, 3.7 or similar - Everytime I attempt to do so, the rate truncates - How can I fix this? is this a remix bug?

 function tokenTransferTwo(address _recipient, uint256 _amount, uint256 _rate) external onlyOwner returns (bool) {
        require(_recipient != address(0));
        require(_amount <= balances[msg.sender]);

        tokensReceived[_recipient] = _amount;
          tokenBalance[_recipient] = _amount;
                  rate[_recipient] = (_rate * 10) / 100; //SafeMath don't work either
        receivedTokens[_recipient] = true;

        balances[msg.sender] = balances[msg.sender].sub(_amount);
        balances[_recipient] = balances[_recipient].add(_amount);

        emit TokensTransferred(msg.sender, _recipient, _amount, rate[_recipient]);
        return true;
NowsyMe
  • 1,365
  • 1
  • 19
  • 37

3 Answers3

6

Solidity does not understand assigning fractional numbers to variables. They should work correctly in calculations (something like 3 / 2 * 6) but you can't assign a fractional result to a variable. Documentation: http://solidity.readthedocs.io/en/develop/types.html#fixed-point-numbers

With Ether / token amounts this is typically not a problem as all amounts are expressed in the smallest indivisible unit (wei in Ether). Typically in token crowdsale contracts the rate is also some rather big numbers, like 100000.

You need to code your contracts so that you don't need to store fractional numbers anywhere. If really needed, you can multiply them for example by 100 and when used in calculations, divide again by 100.

Lauri Peltonen
  • 29,391
  • 3
  • 20
  • 57
1

i made a fraction library with some computations, please check em and let me know any inconveniences or bugs https://github.com/pakchu/Fractions struct [numerator,denominator] which is [uint, uint] -> fraction

Gusgus
  • 11
  • 2
1

Solidity does not support fractional numbers natively, though there are libraries for this. Check ABDK Math 64.64 library. It may do integer/integer->fraction, integer*fraction->integer, as well as all basic math operations with fractions.

Mikhail Vladimirov
  • 7,313
  • 1
  • 23
  • 38
  • Caveat: the ABDK math library works with binary numbers, which has certain implications. For example, 1 is assumed to be 0x10000000000000000 (1 followed by 64 zero bits). – Paul Razvan Berg Mar 17 '21 at 11:49