Solidity 数字格式化库: 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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HongYingClub

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值