Decimal Truncating adding unlimited zeros

I have an entry field for Xamarin forms. Where I have to store the value in a decimal field.

And as per the requirement I have to have the data in ##.#### format.

The validation that it should be less than hundred I am doing it with success.

However I have an issue when truncating the problem.

My Unfocused even for the entry field is as follows.

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();
}

for example if I give value as 99.9999 , I get the value as 99.99990000000000000%

Could you please help me to solve this issue.

Edit: Function AddPercentageSymbol

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

Edit: Expected Outputs

99.9999 = 99.9999%
99.9999766 = 99.9999%
99.99 = 99.99% or 99.9900%
0.76433 = 0.7643%
Jon Skeet
people
quotationmark

I've reproduced this - it looks like it's simply a bug in Mono. It's very easily demonstrated:

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

This should be "0.9", but it's actually "0.9000000000000000000000000000".

Please report a bug in Mono :)

The good news is that you can use Math.Round to get rid of excess digits, e.g.

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

Assuming you were multiplying by 10000, truncating, and then dividing by 10000 to round (down) to 4 digits, you should be able to get away with using Math.Round(value, 4) as by then the value won't have any significant digits after 4 decimal places anyway.

people

See more on this question at Stackoverflow