zoukankan      html  css  js  c++  java
  • C# decimal保留指定的小数位数,不四舍五入

    decimal保留指定位数小数的时候,.NET自带的方法都是四舍五入的。

    项目中遇到分摊金额的情况,最后一条的金额=总金额-已经分摊金额的和。

    这样可能导致最后一条分摊的时候是负数,所以自己写了一个保留指定位数小数的方法。

    扩展方法的使用,使得调用起来很优雅。

     1 public static class DecimalExtension
     2     {
     3         /// <summary>
     4         /// decimal保留指定位数小数
     5         /// </summary>
     6         /// <param name="num">原始数量</param>
     7         /// <param name="scale">保留小数位数</param>
     8         /// <returns>截取指定小数位数后的数量字符串</returns>
     9         public static string ToString(this decimal num, int scale)
    10         {
    11             string numToString = num.ToString();
    12 
    13             int index = numToString.IndexOf(".");
    14             int length = numToString.Length;
    15 
    16             if (index != -1)
    17             {
    18                 return string.Format("{0}.{1}",
    19                     numToString.Substring(0, index),
    20                     numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
    21             }
    22             else
    23             {
    24                 return num.ToString();
    25             }
    26         }
    27     }
    decimal保留指定位数小数
  • 相关阅读:
    3月16日
    11月8日
    Code4 APP
    为什么alertView弹出后button会消失的问题
    设置某个类使用或者禁用ARC
    Bundle使用&NSBundle
    respondsToSelector
    NSDate获取当前时区的时间
    iOS enum 定义与使用
    IOS开发之纯代码界面--基本控件使用篇 ┊
  • 原文地址:https://www.cnblogs.com/tanpeng/p/6133523.html
Copyright © 2011-2022 走看看