C# how to find how many zero after dot in number format

T.Zacks 3,996 Reputation points
2022-04-07T10:40:35.15+00:00

this is a number format in excel stored in string variable like

var format="####0.0%;(####0.0%);####0.0%";

we can see there is one zero after dot but there could be 3 or more zero. so how to write code which will extract how many zeros are there after dot in number format. if possible help me with sample code. thanks

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. T.Zacks 3,996 Reputation points
    2022-04-09T07:42:20.697+00:00

    I have done the job this way.

    public static int DigitCount(string input, char matchChar = '0')
            {
                int count = 0;
                int firstpost = 0;
                int lastpos = 0;
                string actualtext = "";
                //string input = "####0.00%;(####0.0%);####0.0%";
    
                firstpost = input.IndexOf(".") + 1;
                lastpos = input.IndexOf(";");
                actualtext = input.Substring(firstpost, lastpos - firstpost);
                count = actualtext.Count(x => x == matchChar);
    
                return count;
            }
    
    0 comments No comments

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-04-09T10:26:56.017+00:00

    The following code is done for reusability, otherwise the code in Helpers.GetZeros can be placed in a button click for instance.

    191447-f1.png

    Container for results

    public class Container  
    {  
        public int Index { get; set; }  
        public string Value { get; set; }  
        public int Length { get; set; }  
    }  
    

    Work code

    public class Helpers  
    {  
        public static List<Container> GetZeros(string format)  
        {  
            List<Container> list = new List<Container>();  
            Regex regex = new Regex(@"\d+(\.\d+)?");  
            var matches = regex.Matches(format);  
            int index = 0;  
            foreach (Match match in matches)  
            {  
                var length = match.Value.Replace("0.", "").Length;  
                list.Add(new Container() {Index = index, Value = match.Value, Length = length});  
                index++;  
            }  
      
            return list;  
        }  
    }  
    

    Use it

    private void GetZerosButton_Click(object sender, EventArgs e)  
    {  
      
        List<Container> list = Helpers.GetZeros("####0.0%;(####0.00%);####0.0000%");  
      
        Debug.WriteLine("Index     Length    Value ");  
        foreach (var container in list)  
        {  
            Debug.WriteLine($"{container.Index,-10}{container.Length, -10}{container.Value}");  
        }  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.