Solidity

如何將每隔 3 位的分隔逗號添加到輸入整數中?

  • January 15, 2022

有沒有辦法在大輸入數字中添加分隔逗號?假設輸入是 1000,我希望這個函式的輸出是一個格式為“1,000”的轉換字元串。

注意:我正在使用 Openzepplin 單元來字元串庫。

import "@openzeppelin/contracts/utils/Strings.sol";

function myNum(uint256 _Num) public pure returns(string memory){
       return (Strings.toString(_Num));
   }

我建議您使用諸如numericjs 之類的庫在客戶端級別執行此操作。即便如此,這裡有一種直接在solidity中進行的方法。注意:可能有更有效或更清潔的方法。

// SPDX-License-Identifier: GPL-3.0

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol";

pragma solidity 0.8.11;

contract CommaFormatter {

   using Strings for uint256;
   function concat (string memory base, uint256 part, bool isSet) internal pure returns (string memory) {  
           string memory stringified = part.toString();
           string memory glue = ",";

           if(!isSet) glue = "";
           return string(abi.encodePacked(
                   stringified, 
                   glue, 
                   base));
   }

   function format (uint256 source) public pure returns (string memory) {   
       string memory result = "";
       uint128 index;

       while(source > 0) {
           uint256 part = source % 10; // get each digit
           bool isSet = index != 0 && index % 3 == 0; // if we're passed another set of 3 digits, request set glue

           result = concat(result, part, isSet);
           source = source / 10;
           index += 1;
       }

       return result;
   }

}

引用自:https://ethereum.stackexchange.com/questions/118995