开发者

How can I remove all of numbers after the dot?

开发者 https://www.devze.com 2023-01-16 15:10 出处:网络
I\'m making a small tip calculator for the Windows Phone 7 and I\'m almost done: I\'m having trouble getting the trailing deci开发者_Go百科mals places to do what I want though. I want to display th

I'm making a small tip calculator for the Windows Phone 7 and I'm almost done:

How can I remove all of numbers after the dot?

I'm having trouble getting the trailing deci开发者_Go百科mals places to do what I want though. I want to display the result with only two values after the comma. Any suggestions? Here's 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;
}   


You should use currency formatting:

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

For your example, the result would be "$18.90". The benefit of this approach is that the result will be properly localized as well (e.g. some currencies have comma separators instead of ".").

Additionally, if you want to localize the "$" symbol in your UI, you can use NumberFormatInfo.CurrentInfo.CurrencySymbol.


Use

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


two options:

format the string:

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

or round the number using Math.Round which accept a precision parameter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号