C# double和decimal數(shù)據(jù)類型以截斷的方式保留指定的小數(shù)位數(shù)
更新時間:2012年05月23日 15:58:47 作者:
從事ASP.NET in C#開發(fā)快一年了,今天才知道,C#中保留小數(shù)位數(shù)時沒有使用截斷的方式
項目中要用到以截斷的方式取小數(shù)點后兩位,故寫了以下方法:
/// <summary>
/// 將小數(shù)值按指定的小數(shù)位數(shù)截斷
/// </summary>
/// <param name="d">要截斷的小數(shù)</param>
/// <param name="s">小數(shù)位數(shù),s大于等于0,小于等于28</param>
/// <returns></returns>
public static decimal ToFixed(decimal d, int s)
{
decimal sp = Convert.ToDecimal(Math.Pow(10, s));
if (d < 0)
return Math.Truncate(d) + Math.Ceiling((d - Math.Truncate(d)) * sp) / sp;
else
return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp;
}
/// <summary>
/// 將雙精度浮點值按指定的小數(shù)位數(shù)截斷
/// </summary>
/// <param name="d">要截斷的雙精度浮點數(shù)</param>
/// <param name="s">小數(shù)位數(shù),s大于等于0,小于等于15</param>
/// <returns></returns>
public static double ToFixed(double d, int s)
{
double sp = Math.Pow(10, s);
if (d < 0)
return Math.Truncate(d) + Math.Ceiling((d - Math.Truncate(d)) * sp) / sp;
else
return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp;
}
順帶提一下:
double和decimal的ToString("#.##")方法使用的是四舍五入;
靜態(tài)類System.Math下的Round(decimal d, int decimals)方法,舍入的方式使用的是“四舍六入五成雙”;
靜態(tài)類System.Math下的Round(decimal d, int decimals, MidpointRounding mode)的第三個參數(shù)是枚舉參數(shù),指示如何處理中間值(5);
靜態(tài)類System.Math的方法:http://msdn.microsoft.com/zh-cn/library/system.math_methods(v=vs.80)
復制代碼 代碼如下:
/// <summary>
/// 將小數(shù)值按指定的小數(shù)位數(shù)截斷
/// </summary>
/// <param name="d">要截斷的小數(shù)</param>
/// <param name="s">小數(shù)位數(shù),s大于等于0,小于等于28</param>
/// <returns></returns>
public static decimal ToFixed(decimal d, int s)
{
decimal sp = Convert.ToDecimal(Math.Pow(10, s));
if (d < 0)
return Math.Truncate(d) + Math.Ceiling((d - Math.Truncate(d)) * sp) / sp;
else
return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp;
}
/// <summary>
/// 將雙精度浮點值按指定的小數(shù)位數(shù)截斷
/// </summary>
/// <param name="d">要截斷的雙精度浮點數(shù)</param>
/// <param name="s">小數(shù)位數(shù),s大于等于0,小于等于15</param>
/// <returns></returns>
public static double ToFixed(double d, int s)
{
double sp = Math.Pow(10, s);
if (d < 0)
return Math.Truncate(d) + Math.Ceiling((d - Math.Truncate(d)) * sp) / sp;
else
return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp;
}
順帶提一下:
double和decimal的ToString("#.##")方法使用的是四舍五入;
靜態(tài)類System.Math下的Round(decimal d, int decimals)方法,舍入的方式使用的是“四舍六入五成雙”;
靜態(tài)類System.Math下的Round(decimal d, int decimals, MidpointRounding mode)的第三個參數(shù)是枚舉參數(shù),指示如何處理中間值(5);
靜態(tài)類System.Math的方法:http://msdn.microsoft.com/zh-cn/library/system.math_methods(v=vs.80)
相關文章
關于Unity C# Mathf.Abs()取絕對值性能測試詳解
這篇文章主要給大家介紹了關于Unity C# Mathf.Abs()取絕對值性能測試的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Unity C#具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04