Bytes32
當值非常接近時,bytes32 比較返回 true
有這個煩人的問題,其中彼此靠近的 bytes32 在比較時返回 true。
truffle(development)> 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c323821311a == 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c323821311c true truffle(development)> 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c323821311a == 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c323821311d true truffle(development)> 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322d == 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322c true truffle(development)> 0x4b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322d == 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322c false Am I missing something? It is affecting my mapping. Using values that are near to each other causes the same result to be returned.
這是因為 Javascript 使用浮點數來儲存您的數字:
truffle(development)> 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322d 4.1247432523778224e+76 truffle(development)> 0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322c 4.1247432523778224e+76
您想使用 BigNumber 類及其 equals() 函式:
truffle(development)> var a = new web3.BigNumber("0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322c") undefined truffle(development)> var a_again = new web3.BigNumber("0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322c") undefined truffle(development)> var b = new web3.BigNumber("0x5b3138302c3132302c3135392c3232332c36342c3135392c36392c32382c322d") undefined truffle(development)> a.equals(b) false truffle(development)> a.equals(a_again) **true** truffle(development)> a == b false truffle(development)> a == a_again false