[Solved] C# Remove all preceding zeros from a double (no strings) [closed]


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;
}

a more direct, but less intuitive, way using logarithms:

public double RemoveLeadingZeros(double num)
{
    if (num == 0) return 0; 
    if (Math.Abs(num) < 1) {
        double pow = Math.Floor(Math.Log10(num));
        double scale = Math.Pow(10, -pow); 
        num = num * scale;
    }
    return num;
}

it’s the same idea, but multiplying by a power of 10 rather then multiplying several times.

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

9

solved C# Remove all preceding zeros from a double (no strings) [closed]