-1

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?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 2
    *I'm trying to round up numbers using C#* prove it [ask] – Ňɏssa Pøngjǣrdenlarp Nov 03 '14 at 13:32
  • @LuisFilipe: I'm not sure he will since he doesn't want traditional rounding... – Chris Nov 03 '14 at 13:34
  • @LuisFilipe And this will round 0.401 to 0.41? – Renatas M. Nov 03 '14 at 13:38
  • I tried the obvious but I didn't get what I wanted. –  Nov 03 '14 at 13:38
  • [Related](http://stackoverflow.com/q/8844674/1997232), see `Math.Ceiling` answer. – Sinatr Nov 03 '14 at 13:39
  • @LuisFilipe: The key thing about that is it is Midpoint Rounding. That is it is only used on the tiebreaker of whether a 0.5 goes to 0 or 1. It won't make a difference to 0.4 which Round will always put to 0 (assuming 0 decimal places on the round). – Chris Nov 03 '14 at 13:40
  • 1
    @user2506496: What do you consider to be "the obvious?" Including some of your code (especially that which isn't working) will improve your question. – Dan Puzey Nov 03 '14 at 13:46

2 Answers2

5

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

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;
Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325