HI WELCOME TO SIRIS

How to get the total number of decimal places using c#

Leave a Comment
For example, please refer to the sample input and output below. 
InputOutput
10
1.00
1.11
1.122
1.1233
1.11002
1.0102
1.001100 4              


using System;namespace SampleProgram{    class MainProgram    {        public static void Main(string[] args)        {            // Create the decimal array for sample test data            decimal[] decimalNumbers = { 1, 1.0M, 1.1M, 1.12M, 1.123M, 1.1100M,                                                                  1.010M, 1.001100M };
            // Loop thru each decimal number            foreach (decimal decimalNumber in decimalNumbers)            {                // Print the original number and total decimal places                Console.WriteLine("Original Decimal Number = {0}, Total Decimal Places = {1}",                    decimalNumber, GetDecimalPartCount(decimalNumber));            }        }        // Function that return the total decimal places        private static int GetDecimalPartCount(decimal decimalNumber)        {            // Dividing decimal number with 1 gives the decimal part            decimal decimalPlaces = decimalNumber % 1;            if (decimalPlaces != 0)            {                // Get the index of dot from the decimal part                int indexOfDot = decimalPlaces.ToString().IndexOf('.');                // Use the 0.######## format string to rip off trailing zeros, and get the count                int numberOfDecimals =                decimalPlaces.ToString("0.##########").Substring(indexOfDot).Length - 1;
                return numberOfDecimals;            }            // Finally convert decimal to int and return            return (int)decimalPlaces;        }    }}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.