Get number of digits before decimal point

前端 未结 25 1957
独厮守ぢ
独厮守ぢ 2020-12-28 11:53

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should

25条回答
  •  Happy的楠姐
    2020-12-28 12:13

    If you treat zeros or lack of zeroes as 1 number, this is OK. If you want zero to return zero or lack of zero to return zero, then there are a few edge cases to work out which shouldn't be too hard to add. Also, should Absolute value to handle negative numbers. Added that test case as well.

            const decimal d = 123.45m; 
            const decimal d1 = 0.123m;
            const decimal d2 = .567m;
            const decimal d3 = .333m;
            const decimal d4 = -123.45m;
    
            NumberFormatInfo currentProvider = NumberFormatInfo.InvariantInfo;
            var newProvider = (NumberFormatInfo) currentProvider.Clone();
            newProvider.NumberDecimalDigits = 0;
            string number = d.ToString("N", newProvider);  //returns 123 =  .Length = 3
            string number1 = d1.ToString("N", newProvider); //returns 0 = .Length = 1
            string number2 = d2.ToString("N", newProvider); //returns 1 =  .Length = 1
            string number3 = d3.ToString("N", newProvider); //returns 0 =  .Length = 1
            string number4 = Math.Abs(d4).ToString("N", newProvider); //returns 123 =  .Length = 3
    

    Here's a somewhat final solution, if you find a test case that doesn't work, let me know. It should return 3,0,0,0,3 for the test cases provided.

            public static int NumbersInFrontOfDecimal(decimal input)
            {
                NumberFormatInfo currentProvider = NumberFormatInfo.InvariantInfo;
                var newProvider = (NumberFormatInfo)currentProvider.Clone();
                newProvider.NumberDecimalDigits = 0;
    
                var absInput = Math.Abs(input);
                var numbers =  absInput.ToString("N", newProvider);
    
                //Handle Zero and < 1
                if (numbers.Length == 1 && input < 1.0m)
                {
                    return 0;
                }
    
                return numbers.Length;
            }
    

提交回复
热议问题