十进制截断添加无限的零

时间:2014-11-12 07:04:03

标签: c# xamarin

我有一个Xamarin表单的输入字段。我必须将值存储在十进制字段中。

根据要求,我必须以##。####格式提供数据。

验证它应该少于100我正在成功地做到这一点。

但是在截断问题时我遇到了问题。

即使是输入字段,我的Unfocused如下。

private void RateEntry_UnFocused(object sender, FocusEventArgs e)
{
    if (string.IsNullOrEmpty(((Entry)sender).Text))
    {
        ((Entry)sender).Text = "0.00%";
        _ProfileViewModel.Profile.Rate = (decimal)0.00;
    }
    else
    {
        _ProfileViewModel.Profile.Rate = Math.Truncate(Convert.ToDecimal(((Entry)sender).Text)* 10000)/10000;
        ((Entry)sender).Text = AddPercentageSymbol(_ProfileViewModel.Profile.Rate);
    }
    Validate();
}

例如,如果我将值赋予99.9999,我得到的值为99.99990000000000000%

请你帮我解决这个问题。

编辑:功能AddPercentageSymbol

private string AddPercentageSymbol(decimal value)
{
    return string.Format("{0}{1}", value, "%");
}

修改:预期输出

99.9999 = 99.9999%
99.9999766 = 99.9999%
99.99 = 99.99% or 99.9900%
0.76433 = 0.7643%

1 个答案:

答案 0 :(得分:1)

我已经复制了这个 - 看起来它只是Mono中的一个错误。这很容易证明:

decimal x = 9m;
decimal y = x / 10;
Console.WriteLine(y);

这应该是“0.9”,但它实际上是“0.9000000000000000000000000000”。

请报告Mono中的错误:)

好消息是你可以使用Math.Round来消除多余的数字,例如

decimal z = Math.Round(y, 2);
Console.WriteLine(z); // 0.90

假设你乘以10000,截断,然后除以10000再舍入(向下)到4位数,你应该可以使用Math.Round(value, 4),因为那时值不会有任何值无论如何,小数点后4位有效数字。

相关问题