Reputation: 541
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#?
Upvotes: 3
Views: 762
Reputation: 12544
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.
Upvotes: 3
Reputation: 157146
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);
Upvotes: 15