FFA702
FFA702

Reputation: 29

How to shift all the whole numbers in a double to the right of the point

How to shift all the whole numbers in a double to the right of the point ? Example i have 5342, i want the function to return 0.5342. I do not know the number of digits in the double, it's randomly generated. Should be fairly easy but i can't find any answers.

Upvotes: 1

Views: 177

Answers (4)

Veverke
Veverke

Reputation: 11358

private static void Main(string[] args)
{
    Console.WriteLine(MyFunction(5127));
    Console.WriteLine(MyFunction(1));
    Console.WriteLine(MyFunction(51283271));
    Console.WriteLine(MyFunction(-512));
    Console.WriteLine(MyFunction(0));
}

    public static double MyFunction(double myNumber)
    {
        return Math.Floor(myNumber) / Math.Pow(10, Math.Abs(myNumber).ToString().Length);
    }

Output

Upvotes: 3

Just divide by 10 until the number is less than 1.

public static double SomeMethod(double n)
{
    double d = n;
    bool isNegative = (d < 0);
    if(isNegative)
        d = d * -1;

    while(d >= 1)
        d = d/10;

    if(isNegative)
        d = d * -1;

    return d;
}

Alternative (and more precise) option:

public static double SomeMethod2(double n)
{
    double d = n;
    bool isNegative = (d < 0);
    if(isNegative)
        d = d * -1;

    int numberOfDigits = ((int)d).ToString().Length;

    int divisor = 1;
    for(int i = 0; i < numberOfDigits; i++)
        divisor = divisor * 10;

    d = d/divisor;

    if(isNegative)
        d = d * -1;

    return d;
}

Upvotes: 0

user4291562
user4291562

Reputation:

This will get you most of the way there

    public static string test()
    {
        double dub = 5432;

        string dubTxt = dub.ToString();

        string text = "0.";

        string test = string.Concat(text + dubTxt);

        if (1 == 1)
        {

           MessageBox.Show(test);
           return test;

        }
    }

You will have to develop more if statements to handle the negative numbers.

    public static string test()
    {
        double dub = 5432;

        string dubTxt = dub.ToString();

        string text = "0.";

        string test = string.Concat(text + dubTxt);

        if (dub < 0)
        {

              //Do this code instead
        }
    }

Good Luck. Please bump me if you choose it!! I need the cred so I can do other junk. :-D

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500805

This sounds like a pretty bizarre task, to be honest, but you could use:

while (Math.Abs(value) >= 1)
{
    value = value / 10;
}

That will go into an infinite loop if the input is infinity though - and you may well lose information as you keep dividing. The latter point is important - if what you're really interested in is the decimal representation, you should consider using decimal instead of double.

You could potentially use a mixture of Math.Log and Math.Pow to do it, but the above is probably what I'd start with.

Upvotes: 2

Related Questions