Search code examples
c#visual-studio-2005pocketpc

Get last digit from a decimal


I have a question. In my case I want to retrieve the last digit of a decimal value in order to do rounding adjustment. Following is my code:

private void calculateADJ()
    {
        string result = Strings.Right(txtGTotal.Text, 1);
        if (result == "1" || result == "6")
        {
            txtStoreRA.Text = "-0.01";
            txtOutstanding.Text = (Convert.ToDouble(txtGTotal.Text) - 0.01).ToString("0.00");
        }

        if (result == "2" || result == "7")
        {
            txtStoreRA.Text = "-0.02";
            txtOutstanding.Text = (Convert.ToDouble(txtGTotal.Text) - 0.02).ToString("0.00");
        }
        if (result == "3" || result == "8")
        {
            txtStoreRA.Text = "0.01";
            txtOutstanding.Text = (Convert.ToDouble(txtGTotal.Text) + 0.01).ToString("0.00");
        }

        if (result == "4" || result == "9")
        {
            txtStoreRA.Text = "0.02";
            txtOutstanding.Text = (Convert.ToDouble(txtGTotal.Text) + 0.02).ToString("0.00");
        }
        else
        {
            txtOutstanding.Text = txtGTotal.Text;
        }
    }

For example, if the number is 11.93, it will convert it into 11.95. Any suggestion or help will be much appreciate. For your information, I'm doing this with pocket PC emulator 2003 in Visual studio 2005.

My problem is that the value didn't change as I expected.

When I run my program, for example the txtGTotal.Text = 11.94, so my txtOutStanding.Text should be 11.95. However, txtOutStanding.Text still 11.94.

Not sure who is the one who devoting, at least you can provide me the explanation. Getting devote without a reason feels suck, a reason will at least can be a improvement for next time before asking a question. Thank you

I would say Ian's answer is much clearer than the answer provided at the post that I duplicate.


Solution

  • Because your lowest unit is (0.05, which is 1/20th of smallest int 1), the simplest way would be to multiply you value by 20 first before you use Math.Round for the rounding, and then revert it back as needed.

    Or, more simply, you could define this 0.05 as your lowestUnit

    For example, suppose you have:

    txtGTotal.Text = "11.93";    
    double val = double.Parse(txtGTotal.Text);
    

    Do this:

    double myLowestUnit = 0.05;
    double result = myLowestUnit * Math.Round(val/myLowestUnit); //this will give you 11.95
    txtOutStanding.Text = result.ToString("f2"); //use f2 to limit the number of string printed to two decimal places
    

    And to get val from the TextBox, simply use double.Parse(txtGTotal.Text);

    Note that you could use string.ToString("f2") to print the value in the format which you want in your txtOutStanding TextBox.