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

所属分类: 网络编程 / ASP.NET 阅读数: 1343
收藏 0 赞 0 分享

前言

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

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

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

示例代码

public static class DecimalExtension
  {
    /// <summary>
    /// decimal保留指定位数小数
    /// </summary>
    /// <param name="num">原始数量</param>
    /// <param name="scale">保留小数位数</param>
    /// <returns>截取指定小数位数后的数量字符串</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();
      }
    }
  }

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

更多精彩内容其他人还在看

Asp.net中的mail的发送

Asp.net中的mail的发送
收藏 0 赞 0 分享

用ASP.Net实现文件的在线压缩和解压缩

用ASP.Net实现文件的在线压缩和解压缩
收藏 0 赞 0 分享

ASP.NET中文件上传下载方法集合

ASP.NET中文件上传下载方法集合
收藏 0 赞 0 分享

ASP.NET通过Remoting service上传文件

ASP.NET通过Remoting service上传文件
收藏 0 赞 0 分享

ASP.NET2.0服务器控件之Render方法

ASP.NET2.0服务器控件之Render方法
收藏 0 赞 0 分享

ASP.NET2.0 WebRource,开发微调按钮控件

ASP.NET2.0 WebRource,开发微调按钮控件
收藏 0 赞 0 分享

ASP.NET2.0新特性概述

ASP.NET2.0新特性概述
收藏 0 赞 0 分享

介绍几个ASP.NET中容易忽略但却很重要的方法函数

介绍几个ASP.NET中容易忽略但却很重要的方法函数
收藏 0 赞 0 分享

asp.net2.0如何加密数据库联接字符串

asp.net2.0如何加密数据库联接字符串
收藏 0 赞 0 分享

用.NET 2.0压缩/解压功能处理大型数据

用.NET 2.0压缩/解压功能处理大型数据
收藏 0 赞 0 分享
查看更多