user9560865
user9560865

Reputation:

c# calculating digit before floating points

I'm trying to calculate the number of digit before the floating points. for example

input: 123.4

expected output: 3 my actual output: 5

I'm sure there is something wrong with the digit.equals(".") since the program does not break out of the loop.

this is my code:

public class Program
{
    public static void Main()
    {
        Console.WriteLine(HowManyDigit(123.4));
    }

     public static Int32 HowManyDigit(Double number)
        {
            string x = number.ToString();

            var counter = 0;

            for (int i = 0; i < x.Length; i++)
            {
                var digit = x[i];
                //Console.WriteLine(counter);
                if (digit.Equals("."))
                {
                    break;
                }
                else
                {
                    counter++;
                }
            }
            return counter;
        }
}

Upvotes: 0

Views: 94

Answers (5)

Slaven Tojić
Slaven Tojić

Reputation: 3014

Here is a LINQ solution:

double number = 123.4;
var result = number.ToString().TakeWhile(x => char.IsDigit(x)).Count();

Upvotes: 1

maccettura
maccettura

Reputation: 10819

The reason your code does not work breaks down to this logic:

var digit = x[i];
if (digit.Equals("."))
{
    break;
}

The char digit will never be equal to the string "."

If you change your code to:

//Note that I use a char, indicated by ''
if (x[i].Equals('.'))
{
    break;
}

Or simply:

if (x[i] == '.')
{
    break;
}

Either of those two methods will give you a drastically different result from your current code.

That being said, this method is not really the best way of doing what you want. You can simply use IndexOf() to get the exact number you want:

public static int HowManyDigit(double number)
{ 
   return number.ToString().IndexOf('.');
}

Fiddle here

Upvotes: 3

Antoon Verroken
Antoon Verroken

Reputation: 192

Replace this:

if (digit.Equals("."))

With this:

if (digit.Equals('.')) 

Now your output should be 3.

Upvotes: 1

Alexandr Kudryashov
Alexandr Kudryashov

Reputation: 631

Try this x.IndexOf('.') this will be your answer

Upvotes: 1

oliver
oliver

Reputation: 2901

Just compute the logarithm of base 10 and then convert to integer with floor.

n = Math.Floor(Math.Log10(x))+1;

Upvotes: 2

Related Questions