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

一、返回类型 Decimal

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

/// 
/// 十进位计算拓展类
/// 
public static class DecimalExtension
{
    /// 
    /// decimal 保留指定位小数 且不四舍五入
    /// 
    /// 具体数值
    /// 保留小数位数
    /// 
    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;

/// 
/// 十进位计算拓展类
/// 
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;
        }
    }
}

你可能感兴趣的:(unity实战篇,unity,c#,游戏引擎)