How can I remove all numbers after a dot?

I'm making a small tip calculator for Windows Phone 7, and I'm almost ready:

alt text

I am having problems so that the final decimal places can do what I want. I want to show the result with only two decimal places. Any suggestions? Here is my code:

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
    if (ValidateInputs())
    {
        lblTotalTip.Text = CalculateTip(txtTotalBill.Text, txtPercentage.Text);                
    }
}

private string CalculateTip(string Total, string Percentage)
{
    decimal totalBill = decimal.Parse(Total);
    decimal percentage = decimal.Parse(Percentage);

    string result = ((percentage / 100) * totalBill).ToString();
    return result;
}

private bool ValidateInputs()
{
    return true;
}   
+3
source share
3 answers

You should use currency formatting:

string result = ((percentage / 100) * totalBill).ToString("C");

In your example, the result would be "$ 18.90." The advantage of this approach is that the result will also be correctly localized (for example, some currencies have comma delimiters instead of ".").

, "$" , NumberFormatInfo.CurrentInfo.CurrencySymbol.

+15

    string result = ((percentage / 100) * totalBill).ToString("0.00");
+1

:

:

string.Format("{0:#####.00}", theValue)

or round a number using Math.Roundthose that accept the precision parameter.

0
source

Source: https://habr.com/ru/post/1765538/


All Articles