Home > Software design >  C# Remove all preceding zeros from a double (no strings)
C# Remove all preceding zeros from a double (no strings)

Time:08-31

I need a method to return the firsts non zero numbers from a double in the following way:

double NumberA = 123.2; // Returns 123.2 (returns the same as it does not start with 0)
double NumberB = 1.2; // Returns 1.2 (returns the same as it does not start with 0)
double NumberC = 0.000034; // Returns 3.4
double NumberD = 0.3; // Returns 3.0
double NumberE = -0.00000087; // Returns -8.7

CodePudding user response:

One option would be to iteratively multiply by 10 until you get a number greater than 1:

public double RemoveLeadingZeros(double num)
{
    if (num == 0) return 0; 
    while(Math.Abs(num) < 1) { num *= 10};
    return num;
}

Note that double arithmetic is not always precise; you may end up with something like 3.40000000001 or 3.3999999999. If you want absolute precision then you can use decimal instead, or string manipulation.

CodePudding user response:

I would start with converting to a string. Something like this:

string doubleString = NumberC.ToString();

I don't know exactly what this will output, you will have to check. But if for example it is "0.000034" you can easily manipulate the string to meet your needs.

  •  Tags:  
  • c#
  • Related