You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中正确格式化Ethplorer API返回的余额数值

问题:Ethplorer API余额的C#格式化实现

需求说明

从Ethplorer API获取的余额为整数形式(对应代币最小单位),需要格式化为以下样式:

  • 千分位用.分隔
  • 小数部分用,开头
  • 小数位保留规则:若小数部分全为0则保留两位,否则保留所有有效数位

格式示例:

  • 100000000000000 => 100.000.000,00
  • 254107403768716 => 254.107.403,768716
  • 751685000000 => 751.685,00
  • 679447550000 => 679.447,55

当前问题

直接对整数进行格式化会错误地将整个数字视为整数部分,导致输出不符合预期:

var balance = 100000000000000;

Console.WriteLine(String.Format("{0:#,##0.00}", balance));
// 输出: 100.000.000.000.000,00

Console.WriteLine(balance.ToString("###,###,###"));
// 输出: 100.000.000.000.000

// 预期: 100.000.000,00

解决方案

核心思路

  1. 先将整数余额转换为实际代币数量:除以代币的小数位数次方(示例中代币为6位小数,需根据实际代币调整)
  2. 自定义数字格式规则,替换千分位和小数分隔符
  3. 根据小数部分是否为0,动态选择格式化规则

代码实现

using System.Globalization;

// 示例余额
long balance = 100000000000000;
// 代币小数位数(示例为6,需根据实际代币修改)
int tokenDecimalPlaces = 6;

// 转换为实际代币数量
decimal actualValue = balance / (decimal)Math.Pow(10, tokenDecimalPlaces);

// 自定义格式信息
var customFormat = new NumberFormatInfo
{
    NumberGroupSeparator = ".",
    NumberDecimalSeparator = ","
};

// 动态选择格式化规则
string formattedResult = actualValue % 1 == 0 
    ? actualValue.ToString("N2", customFormat) 
    : actualValue.ToString("G", customFormat);

Console.WriteLine(formattedResult);
// 输出: 100.000.000,00

// 测试其他示例
balance = 254107403768716;
actualValue = balance / (decimal)Math.Pow(10, tokenDecimalPlaces);
formattedResult = actualValue % 1 == 0 
    ? actualValue.ToString("N2", customFormat) 
    : actualValue.ToString("G", customFormat);
Console.WriteLine(formattedResult);
// 输出: 254.107.403,768716

balance = 751685000000;
actualValue = balance / (decimal)Math.Pow(10, tokenDecimalPlaces);
formattedResult = actualValue % 1 == 0 
    ? actualValue.ToString("N2", customFormat) 
    : actualValue.ToString("G", customFormat);
Console.WriteLine(formattedResult);
// 输出: 751.685,00

balance = 679447550000;
actualValue = balance / (decimal)Math.Pow(10, tokenDecimalPlaces);
formattedResult = actualValue % 1 == 0 
    ? actualValue.ToString("N2", customFormat) 
    : actualValue.ToString("G", customFormat);
Console.WriteLine(formattedResult);
// 输出: 679.447,55

关键说明

  • tokenDecimalPlaces需根据对应代币的小数位数调整(比如ETH是18位)
  • NumberFormatInfo用于替换默认的分隔符,匹配需求格式
  • 用actualValue % 1 == 0判断小数部分是否全为0,动态切换格式化规则,实现示例中的小数位保留逻辑

内容的提问来源于stack exchange,提问作者Charpit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:40:42