using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YB.DeviceStand.Util.Extend
{
    public static partial class Ext
    {
        /// <summary>
        /// 转换为高精度浮点数,并按指定的小数位4舍5入
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="digits">小数位数</param>
        public static decimal ToDecimal(this object data, int digits)
        {
            var result = ToDecimal(data);
            string numToString = result.ToString();
            int index = numToString.IndexOf(".");
            int length = numToString.Length;
            if (index != -1)
            {
                numToString = string.Format("{0}.{1}",
                    numToString.Substring(0, index),
                    numToString.Substring(index + 1, Math.Min(length - index - 1, digits)));
            }
            return ToDecimal(numToString);
            //return Math.Round(ToDecimal(numToString), digits);
        }
        /// <summary>
        /// 转换为高精度浮点数
        /// </summary>
        /// <param name="data">数据</param>
        public static decimal ToDecimal(this object data)
        {
            if (data == null)
                return 0;
            decimal result;
            string val = data.ToString().Replace(" ", "");
            return decimal.TryParse(val, out result) ? result : 0;
        }
    }
}
