'C# decimal take ceiling 2
I want to round my decimal value like 2.2222 to 2.23. When I use round,
decimal a = Math.Round((decimal)2.222, 2);
When I use ceiling, it cause 3
decimal c = Math.Ceiling((decimal)2.22);
How can I get 2.2222 to 2.23 ?
Solution 1:[1]
public static decimal CeilingAfterPoint(this decimal number, int digitsAfterPoint) {
return Math.Ceiling(number * (decimal)Math.Pow(10, digitsAfterPoint))
/ (decimal)Math.Pow(10, digitsAfterPoint);
}
Solution 2:[2]
decimal c = Math.Ceiling((decimal)2.2222*100)/100;
but it's stupid.
Solution 3:[3]
try something like
decimal c = Math.Ceiling((decimal)2.222*100)/100;
but it fails if your value is 2.22
Solution 4:[4]
Legacy question. But it deserves a right answer. Since .net core 3 you have been able to round decimals the following way:
Decimal.Round(2.222m, 2, MidpointRounding.ToPositiveInfinity);
It rounds upwards for the 2nd decimal.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | linkerro |
| Solution 3 | dotNETbeginner |
| Solution 4 | Kent Kostelac |
