Difficulty in eliminating zero values ​​in decimal numbers?

advertisements

I wrote a code that will sort based on decimals. The quick sort algorithm. But my issue is the removal of the number 0 in some decimals. Eg 723.1000 becomes 723.1 Numbers are important to me because I want to be displayed and stored as

Now how can I do this without removing the zeros in decimal numbers

We may see these numbers in an array

Zeros will not be removed.

10.20 ==> 10.2

or

50.60000 ==> 50.6

or

145698.154780 ===> 145698.15478

So many zeros are not fixed

And this is my problem.

internal class Sorter
{
    public string[] QuickSort(string[] array, int low, int high)
    {
        if (low < high)
        {
            int p = Partition(array, low, high);
            QuickSort(array, low, p - 1);
            QuickSort(array, p + 1, high);
        }

        return array;
    }

    private static int Partition(string[] array, int low, int high)
    {
        int left = low + 1, right = high;
        string temp;
        double pivot = double.Parse(array[low]);
        int piv;

        while (left <= right)
        {
            while (left <= right && Convert.ToDouble(array[left]) <= pivot)

                left++;

            while (left <= right && Convert.ToDouble(array[right]) >= pivot)

                right--;

            if (left < right)
            {
                temp = array[left];
                array[left] = array[right];
                array[right] = temp;
            }
        }
        if (right == high)
            piv = high;
        else if (right == low)
            piv = low;
        else
            piv = left - 1;
        array[low] = array[piv];
        array[piv] = pivot.ToString();
        return piv;
    }
}


You can try with Double.ToString():

   double d=723.1000;
   string s = d.ToString("0.0");

Check here for more formatting options.

Update You can try this :

string s = d.ToString().TrimEnd('0');

Update 2: As discussed here :

double doesn't keep insignificant digits - there's no difference between 1.5 and 1.50000 as far as double is concerned.

If you want to preserve insignificant digits, use decimal instead. It may well be more appropriate for you anyway, depending on your exact context. (We have very little context to go on here...)

So you can use this decimal instead of double:

decimal d = 723.1000M;
string s = d.ToString();