推荐一个Solidity 数字格式化库: solpretty

  • ChainTool
  • 更新于 2023-09-14 22:48
  • 阅读 1478

合约里的数值通常非常大, 肉眼阅读非常费劲,solpretty 可以让对数字进行漂亮的格式化。

合约里的数值通常非常大, 肉眼阅读非常费劲,solpretty 可以让对数字进行漂亮的格式化。

solpretty 在 Foundry 工程下使用:

使用 Foundry install 安装 solpretty:

forge install devtooligan/solpretty

solpretty 用法

pp 格式化

solpretty 提供了 pp 函数:

  • pp(uint256 value)
  • pp(uint256 value, uint256 fixedDecimals)
  • pp(uint256 value, uint256 fixedDecimals, uint256 displayDecimals)
  • pp(uint256 value, uint256 fixedDecimals, uint256 displayDecimals, uint256 fixedWidth)
  • pp(uint256 value, memory SolPrettyOptions)

不同的参数,用来支持不同的格式化显示效果, pp 函数返回的是格式化后的在字符串。

例如(注释字符串为 pp 函数返回结果):

import {pp} from "solpretty/SolPretty.sol";

pp(123123123123) //            -> "123,123,123,123" //  default
pp(123123123123, 6) //         -> "123,123.123123" //   fixedDecimals = 6
pp(123123123123, 6, 2) //      -> "123,123.12" //       displayDecimals = 2
pp(123123123123, 6, 0, 15) //  -> "         123,123" // fixedWidth = 15

还可自定义选项:

SolPrettyOptions memory solPrettyOptions = getDefaultOptions();

SolPrettyOptions.fixedDecimals = 6;
SolPrettyOptions.fixedWidth = 20;
SolPrettyOptions.decimalDelimeter = bytes1("*");
SolPrettyOptions.integerDelimeter = bytes1(" ");

pp(123123123123, solPrettyOptions); // -> "      123 123*123123"

// 
struct SolPrettyOptions {
    uint256 fixedDecimals; //          default 0
    uint256 displayDecimals; //        default type(uint256).max
    bytes1 decimalDelimter; //         default "."
    bytes1 fractionalDelimiter; //     default " "
    uint256 fractionalGroupingSize; // default 0
    bytes1 integerDelimiter; //        default ","
    uint256 integerGroupingSize; //    default 3
    uint256 fixedWidth; //             default 0 (automatic)
}

concat

solpretty 还支持和字符串拼接,有两个拼接方法:

  • concat(string memory left, string memory right)
  • concat(string[] memory parts)

一个用于字符串拼接,一个用于字符串数组拼接, 例如:

import {pp, SolPretty} from "solpretty/SolPretty.sol";
using SolPretty for string;

pp(1234).concat(" Alice's balance"); // -> "1,234 Alice's Balance";

// 字符串数组拼接
string[] memory strings = new string[](3);
strings[0] = "a";
strings[1] = "b";
strings[2] = "c";
concat(strings); // -> "abc"

log 打印

solpretty 支持把格式好的字符串打印输出:

  • log(string memory message)
  • log(string[] memory messages)

例如:

using SolPretty for string;

log("hoagies"); // console2.log("hoagies");
pp(1234).log(); // console2.log("1,234")
pp(1234).concat(" Alice's balance").log(); // console2.log("1,234 Alice's balance")

本文来自ChainTool,http://chaintool.tech 是一个为帮助开发者提高效率的开源区块链开发工具。

Solidity 开发基础测试 完成挑战,领取SBT,给你的链上履历加一笔成就 !
开始挑战
点赞 2
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
ChainTool
ChainTool
https://chaintool.tech/ ChainToolDAO 致力于为开发者提供高效、易用、开源的区块链开发工具,我们的成员不仅仅是贡献者,也是自己产品的用户,我们构建自己喜欢的产品的同时,让更多的人受益。