欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.net decimal保留指定的小數(shù)位數(shù)(不四舍五入)

 更新時(shí)間:2016年12月07日 10:26:57   作者:pengtan  
大家都知道decimal保留指定位數(shù)小數(shù)的時(shí)候,.NET自帶的方法都是四舍五入的。那么如何讓decimal保留指定位數(shù)小數(shù)的時(shí)候不四舍五入呢,下面通過這篇文中的示例代碼來一起看看吧。

前言

項(xiàng)目中遇到分?jǐn)偨痤~的情況,最后一條的金額=總金額-已經(jīng)分?jǐn)偨痤~的和。

這樣可能導(dǎo)致最后一條分?jǐn)偟臅r(shí)候是負(fù)數(shù),所以自己寫了一個(gè)保留指定位數(shù)小數(shù)的方法。

擴(kuò)展方法的使用,使得調(diào)用起來很優(yōu)雅。

示例代碼

public static class DecimalExtension
  {
    /// <summary>
    /// decimal保留指定位數(shù)小數(shù)
    /// </summary>
    /// <param name="num">原始數(shù)量</param>
    /// <param name="scale">保留小數(shù)位數(shù)</param>
    /// <returns>截取指定小數(shù)位數(shù)后的數(shù)量字符串</returns>
    public static string ToString(this decimal num, int scale)
    {
      string numToString = num.ToString();

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

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

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

最新評(píng)論