unity工具类篇 Decimal保留n位小数点,且不四舍五入

一、返回类型 Decimal

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 十进位计算拓展类
/// </summary>
public static class DecimalExtension
{
    
    
    /// <summary>
    /// decimal 保留指定位小数 且不四舍五入
    /// </summary>
    /// <param name="num">具体数值</param>
    /// <param name="scale">保留小数位数</param>
    /// <returns></returns>
    public static decimal DecimalToString(decimal num,int scale) {
    
    
        string numToString = num.ToString();

        int index = numToString.IndexOf(".");
        int length = numToString.Length;

        if (index != -1)
        {
    
    
            string dm = string.Format("{0}.{1}",
            numToString.Substring(0,index),
            numToString.Substring(index + 1, Mathf.Min(length - index - 1, scale)));
            return System.Convert.ToDecimal(dm);
        }
        else {
    
    
            string dm = num.ToString();
            return System.Convert.ToDecimal(dm);
        }
    }
}

二、返回类型 string

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 十进位计算拓展类
/// </summary>
public static class DecimalExtension
{
    
    
    public static string DecimalToString(decimal num,int scale) {
    
    
        string numToString = num.ToString();

        int index = numToString.IndexOf(".");
        int length = numToString.Length;

        if (index != -1)
        {
    
    
            string dm = string.Format("{0}.{1}",
            numToString.Substring(0,index),
            numToString.Substring(index + 1, Mathf.Min(length - index - 1, scale)));
            return dm;
        }
        else {
    
    
            string dm = num.ToString();
            return dm;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44720673/article/details/125394021