是的,新的已经修改,是缺少了类型定义。您可以使用以下代码:
- /// <function name="AutoFormat">
- /// <culture>
- /// <label>AutoFormat</label>
- /// <syntax>AutoFormat(object number, string unit = "", string format = "")</syntax>
- /// <description>自动转换中文单位</description>
- /// <example>AutoFormat(100) = 100
- /// AutoFormat(100000,"万") = 10.0万 (万与亿自动单位 1位小数)
- /// AutoFormat(100000,"万","0:0.00") = 10.00万 (可以用第二个参数自定义小数位数和格式化)
- /// </example>
- /// </culture>
- /// </function>
- public string AutoFormat(object number, string unit = "", string format = "")
- {
- // 文本对应的数值单位
- System.Collections.Generic.Dictionary<string, decimal> unitDic = new System.Collections.Generic.Dictionary<string, decimal>() {
- {"百",100},{"千",1000},{"万",10000},{"十万",100000},{"百万",1000000},{"千万",10000000},{"亿",100000000},{"十亿",1000000000},{"万亿",1000000000000}
- };
- if (number == null)
- return string.Empty;
- try
- {
- // 如果不传单位,就根据数值自动判断单位(亿和万)
- var result = Convert.ToDecimal(number);
- if (string.IsNullOrWhiteSpace(unit))
- {
- if (Math.Abs(result) >= 100000000)
- {
- unit = "亿";
- }
- else if(Math.Abs(result) >= 10000)
- {
- unit = "万";
- }
- }
-
- if (unitDic.ContainsKey(unit))
- {
- // 如果是有文字单位,自动保留1位小数
- if (string.IsNullOrEmpty(format)) format = "{0:0.0}";
- return String.Format(format + unit, result / unitDic[unit]);
- }
- // 如果传了format,就用format,如果没有传就用自带toString()
- return string.IsNullOrWhiteSpace(format)? result.ToString():String.Format(format, result);
- }
- catch (Exception e)
- {
- return "AutoFormat转换错误"+e.Message;
- }
- }
复制代码
|