3

I want to round off decimal if the value is 0.7 greater

Sample:

decimal rate = 3.7
decimal roundoff = 4 

decimal rate2 = 3.6
decimal roundoff2 = 3.6 //remain value coz its below 0.7

how can i do that in c#?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
comfreakph
  • 549
  • 2
  • 6
  • 20

2 Answers2

15

You can use modulus to calculate the remainder:

decimal d = rate % 1 >= .7m ? Math.Ceiling(rate) : rate;

You could use this for negative values:

return rate >= 0
       ? (rate % 1 >= .7m ? Math.Ceiling(rate) : rate) 
       : (Math.Abs(rate % 1) >= .3m ? Math.Floor(rate) : rate);
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • I think there's some _minor_ errors: `.7` should be `.7m` and `Math.Ceil` should be `Math.Ceiling`. Also, this doesn't seem to work at all for negative numbers (always returning `rate`), but the question didn't specify how those should be handled. – Chris Sinclair Apr 30 '14 at 15:06
  • 1
    @ChrisSinclair: Thanks. Just wrote it from the top of my head. Also included a version handling negative values. – Patrick Hofman Apr 30 '14 at 15:09
  • Regarding the edit for use with negative numbers, this will round it incorrectly _toward_ zero. That is: -3.7 => -3.0; -3.6 => -3.6. Switching it to use `Math.Floor` will have them round _away_ from zero (-3.7 => -4.0; -3.6 => -3.6) which is probably what was intended. – Chris Sinclair Apr 30 '14 at 15:11
  • 1
    No problem. I don't think it's _too_ worthwhile to worry much about the negative case, at least not until comfreakph clarifies how negative numbers should be handled (if at all) +1 regardless! – Chris Sinclair Apr 30 '14 at 15:15
3

Purely because I couldn't resist trying a mathematical equivalent:

rate + (int)((rate % 1) / 0.7m) * (1 - Math.Abs(rate % 1));

Just can't get rid of the Math.Abs yet to make if completely without calls. If only positive numbers are used, the math.abs can be omitted as is.

Me.Name
  • 12,259
  • 3
  • 31
  • 48