请选择 进入手机版 | 继续访问电脑版
 找回密码
 立即注册

QQ登录

只需一步,快速开始

Tony.Fu 活字格认证 Wyn认证
超级版主   /  发表于:2022-10-24 14:47  /   查看:1232  /  回复:0
本帖最后由 James.Lv 于 2023-1-5 17:54 编辑

===前言===
  熟悉仪表板的同学 都应该用过仪表板的 自动单位功能,如图:
image.png330523375.png
  数据单位会自动根据数值切换成(万/亿),并自动保留1位小数
   而本帖会通过【自定义函数】功能,在报表中实现相同的效果
image.png886492004.png

===实现步骤===
1.打开后台管理 → 系统设置 → 报表设置 → 自定义函数,添加如下内容
   1666584096112.jpg130245360.png
  1. /// <function name="AutoFormat">
  2. /// <culture>
  3. /// <label>AutoFormat</label>
  4. /// <syntax>AutoFormat(object number, string unit = "", string format = "")</syntax>
  5. /// <description>自动转换中文单位</description>
  6. /// <example>AutoFormat(100) = 100
  7. /// AutoFormat(100000,"万") = 10.0万 (万与亿自动单位 1位小数)
  8. /// AutoFormat(100000,"万","{0:0.00") = 10.00万 (可以用第二个参数自定义小数位数和格式化)
  9. /// </example>
  10. /// </culture>
  11. /// </function>
  12. public string AutoFormat(object number, string unit = "", string format = "")
  13. {
  14.     // 文本对应的数值单位
  15.     Dictionary<string, decimal> unitDic = new Dictionary<string, decimal>() {
  16.         { "百",100},{ "千",1000},{ "万",10000},{ "十万",100000},{ "百万",1000000},{ "千万",10000000},{ "亿",100000000},{ "十亿",1000000000},{ "万亿",1000000000000}
  17.     };

  18.     if (number == null)
  19.         return string.Empty;
  20.     try
  21.     {
  22.         // 如果不传单位,就根据数值自动判断单位(亿和万)
  23.         var result = Convert.ToDecimal(number);
  24.         if (string.IsNullOrWhiteSpace(unit))
  25.         {
  26.             if (Math.Abs(result) >= 100000000)
  27.             {
  28.                 unit = "亿";
  29.             }
  30.             else if(Math.Abs(result) >= 10000)
  31.             {
  32.                 unit = "万";
  33.             }
  34.         }
  35.         
  36.         if (unitDic.ContainsKey(unit))
  37.         {
  38.             // 如果是有文字单位,自动保留1位小数
  39.             if (string.IsNullOrEmpty(format)) format = "{0:0.0}";
  40.             return String.Format(format + unit, result / unitDic[unit]);
  41.         }
  42.         // 如果传了format,就用format,如果没有传就用自带toString()
  43.         return string.IsNullOrWhiteSpace(format)? result.ToString():String.Format(format, result);
  44.     }
  45.     catch (Exception e)
  46.     {
  47.         return "AutoFormat转换错误"+e.Message;
  48.     }
  49. }
复制代码
2.编译并保存
image.png859149780.png

3.然后报表中可以通过 Code.AutoFormat 来使用
===举个栗子===
image.png267107543.png
报表中代码如下:
1.自动单位, 不加参数时, 小于一万 不处理 {Code.AutoFormat(123.45)}
2.自动, 不加参数时, 万和亿自动一位小数, 四舍五入  {Code.AutoFormat(12345.67, "", "")}
3.手动指定某个单位  {Code.AutoFormat(12345, "千", "")}
4.自动单位+格式化,保留3位小数  {Code.AutoFormat(12345.6789, "", "{0:0.000}")}
5.手动指定单位+四舍五入小数部分  {Code.AutoFormat(12345.6789, "百", "{0:0}")}



0 个回复

您需要登录后才可以回帖 登录 | 立即注册
返回顶部