unity工具类篇 Decimal保留n位小数点,且不四舍五入
Posted 彭老希
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
以上是关于unity工具类篇 Decimal保留n位小数点,且不四舍五入的主要内容,如果未能解决你的问题,请参考以下文章