Reputation: 291
I have a method which auto calculates an amount based on user input. My requirement is to set the scale as 4 for that number. E.G if the amount is 49, it should return 49.0000. If the amount is 49.2412412414, it should return 49.2412. I have used Math.Round(), but it doesn't work for example 1. i.e. it fails to convert 49 to 49.0000. My sample code:
private decimal getAmount(decimal rate)
{
decimal Amount = 0;
Amount = 12 * rate;
return Math.Round(Amount, 4);
}
Upvotes: 1
Views: 190
Reputation: 9463
You have to differentiate between the numeric reperesentation and the string representation. A decimal
will ignore any trailing zeros. But you can force the trailing zeros to be displayed if you convert the decimal to a string
.
decimal amount = 49.0M;
var rounded = Math.Round(amount, 4);
string display = rounded.ToString("#.0000", CultureInfo.InvariantCulture); // "49.0000"
Upvotes: 1
Reputation: 2466
You can multiply the Amount by 1.0000M
to get the desired result. Your code would be like:
private decimal getAmount(decimal rate)
{
decimal Amount = 0;
Amount = 12 * rate;
Amount *= 1.0000M;
return Math.Round(Amount, 4);
}
However, as stated in MSDN:
Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.
So, 49 is actully equal to 49.0000, but if you want a string representation of the value you can change your function to the following:
private static string getAmount(decimal rate)
{
decimal Amount = 0;
Amount = 12 * rate;
return Amount.ToString("#.0000", CultureInfo.InvariantCulture);
}
Upvotes: 1