Solidity – Can Floating Point Numbers Be Used in Solidity?

solidity

in this contract will the floating point work,

pragma solidity ^0.8.7;

// SPDX-License-Identifier: GPL-3.0


contract AB {

   address payable  b= payable(xx);

    uint amount= 0.1 ether;
  


     function Optimizer( uint256 _amount )public  payable{

        
     _amount=msg.value;
        
       require(amount >=0.1 ether,"transfer amount to low");

      

      b.transfer(msg.value);

      
       
    }
    
}

Best Answer

yes, you used the ether keyword with a floating point correctly. In Remix your 0.1 ether line didn't cause any warnings or errors.

If you create a test function that returns 0.1 ether, you can see that it really returns 100000000000000000:

function test() public pure returns(uint){

    return 0.1 ether;
    }

enter image description here

If you put this WEI value into an Ethereum unit converter, you can see the number's equivalent in GWEI and ETH:

enter image description here

A more refined version of your contract that uses msg.value correctly as opposed to your _amount uint, custom errors as opposed to your hard-coded require, and call instead of transfer for sending the ETH:



contract AB {

  error CallFailed();
  error TransferAmountTooLow();

    uint amount= 0.1 ether;
    address payable b = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);


     function Optimizer( )public  payable{ 
      if(msg.value < 0.1 ether) {
        revert TransferAmountTooLow();
      }
      (bool sent,) = b.call{value: msg.value}("");
      if(!sent) {
        revert CallFailed();
      }    
    }
    
}
Related Topic