Calculate System.Decimal Precision and Scale

前端 未结 5 1712
我寻月下人不归
我寻月下人不归 2020-12-01 01:01

Suppose that we have a System.Decimal number.

For illustration, let\'s take one whose ToString() representation is as follows:

d.ToString() = \"123.4         


        
5条回答
  •  无人及你
    2020-12-01 01:28

    public static class DecimalExtensions
    {
        public static int GetPrecision(this decimal value)
        {
            return GetLeftNumberOfDigits(value) + GetRightNumberOfDigits(value);
        }
    
        public static int GetScale(this decimal value)
        {
            return GetRightNumberOfDigits(value);
        }
        /// 
        /// Number of digits to the right of the decimal point without ending zeros
        /// 
        /// 
        /// 
        public static int GetRightNumberOfDigits(this decimal value)
        {
            var text = value.ToString(System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0');
            var decpoint = text.IndexOf(System.Globalization.CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
            if (decpoint < 0)
                return 0;
            return text.Length - decpoint - 1;
        }
    
        /// 
        /// Number of digits to the left of the decimal point without starting zeros
        /// 
        /// 
        /// 
        public static int GetLeftNumberOfDigits(this decimal value)
        {
            var text = Math.Abs(value).ToString(System.Globalization.CultureInfo.InvariantCulture).TrimStart('0');
            var decpoint = text.IndexOf(System.Globalization.CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
            if (decpoint == -1)
                return text.Length;
            return decpoint;
        }
    }
    

    My solution is compatible with Oracle precision and scale definition for NUMBER(p,s) DataType:

    https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#i16209

    Regards.

提交回复
热议问题