I'm trying to round up numbers using C# in a way that it always rounds to the next number. For instance:
0.409 -> 0.41
0.401 -> 0.41
0.414 -> 0.42
0.499 -> 0.50
0.433 -> 0.44
Is there a way to do this using .NET built-in functions?
I'm trying to round up numbers using C# in a way that it always rounds to the next number. For instance:
0.409 -> 0.41
0.401 -> 0.41
0.414 -> 0.42
0.499 -> 0.50
0.433 -> 0.44
Is there a way to do this using .NET built-in functions?
Math.Ceiling
can be used.
Math.Ceiling
rounds to the nearest integer though, so I advise you do some division/multiplication also:
var notRounded = 0.409;
var rounded = Math.Ceiling(notRounded * 100) / 100;
Explanation: notRounded
* 100 gives you 40.9. Math.Ceiling
will return 41, so divide this again to 'restore it' back to the original decimal form: 0.41.
One way would be Math.Ceiling
as already described.
Another option is to calculate the remainder, and add the difference to round up:
decimal r = 0.409M;
decimal d = r % .01M > 0 ? (r + .01M - r % .01M) : r;