Try using decimal.Round():
decimal.Round(x, 2)
Where x
is your value and 2 is the number of decimals you wish to keep.
You can also specify whether .5 rounds up or down by passing third parameter:
decimal.Round(x, 2, MidpointRounding.AwayFromZero);
EDIT:
In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:
var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;
Truncate() lops off the non-integer portion of the decimal. Note that numDigits
above should be how many digits you want to KEEP, not the total number of decimals, etc.
Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate()
call before dividing again.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…