c#将long型数字转换成最多固定长度的字符串

这段代码定义了一个名为convertUnitLengthLimit的方法,用于将长整型数值转换为带有合适单位(如KB、MB等)的字符串,当数值过大时,会进行科学计数法表示。

public static string convertUnitLengthLimit(long num, int most)

    {

        // string strNum = string.Empty + num;

        string strNum = num.ToString("D");

        if (strNum.Length <= most)

        {

            return num.ToString("n0");

        }

        most -= 1;

        string[] unitStrs = { string.Empty, "K", "M", "B","T" };    //单位

        int lost = 0;

        while (strNum.Length - lost > most)

        {

            lost += 1;

        }

        int decimalsNum = 3 - (lost % 3);

        if (decimalsNum == 3) decimalsNum = 0;

        int unitIndex = (lost + decimalsNum) / 3;

        while (unitIndex > 3)

        {

            lost -= 3;

            unitIndex -= 1;

        }

        double mostShow = num / (double)Math.Pow(10, lost + decimalsNum);

        return mostShow.ToString("N" + decimalsNum) + unitStrs[unitIndex];

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值