using System;
public class Test
{
public static void Main()
{
for (decimal x = 1 ; x != 2 ; x+=0.01M) {
decimal y = CashRound(x);
Console.WriteLine("{0:0.00} {1:0.00}", x, y);
}
}
public static decimal CashRound(decimal value, decimal cents = 0.05m)
{
var roundedValue = Math.Truncate(value * 100) / 100; // ensure internal value has 2 decimals
var modToCents = roundedValue * 100 % (cents * 100);
if (modToCents == 0)
return roundedValue;
else if (modToCents < 3)
roundedValue -= modToCents / 100;
else if (modToCents < 8)
roundedValue += cents - modToCents / 100;
else
roundedValue += modToCents / 100;
return roundedValue;
}
}
dXNpbmcgU3lzdGVtOwoKcHVibGljIGNsYXNzIFRlc3QKewoJcHVibGljIHN0YXRpYyB2b2lkIE1haW4oKQoJewoJCWZvciAoZGVjaW1hbCB4ID0gMSA7IHggIT0gMiA7IHgrPTAuMDFNKSB7CgkJCWRlY2ltYWwgeSA9IENhc2hSb3VuZCh4KTsKCQkJQ29uc29sZS5Xcml0ZUxpbmUoInswOjAuMDB9IHsxOjAuMDB9IiwgeCwgeSk7CgkJfQoJfQoJCiAgICBwdWJsaWMgc3RhdGljIGRlY2ltYWwgQ2FzaFJvdW5kKGRlY2ltYWwgdmFsdWUsIGRlY2ltYWwgY2VudHMgPSAwLjA1bSkKICAgIHsKICAgICAgdmFyIHJvdW5kZWRWYWx1ZSA9IE1hdGguVHJ1bmNhdGUodmFsdWUgKiAxMDApIC8gMTAwOyAvLyBlbnN1cmUgaW50ZXJuYWwgdmFsdWUgaGFzIDIgZGVjaW1hbHMKCiAgICAgIHZhciBtb2RUb0NlbnRzID0gcm91bmRlZFZhbHVlICogMTAwICUgKGNlbnRzICogMTAwKTsKICAgICAgaWYgKG1vZFRvQ2VudHMgPT0gMCkKICAgICAgICByZXR1cm4gcm91bmRlZFZhbHVlOwogICAgICBlbHNlIGlmIChtb2RUb0NlbnRzIDwgMykKICAgICAgICByb3VuZGVkVmFsdWUgLT0gbW9kVG9DZW50cyAvIDEwMDsKICAgICAgZWxzZSBpZiAobW9kVG9DZW50cyA8IDgpCiAgICAgICAgcm91bmRlZFZhbHVlICs9IGNlbnRzIC0gbW9kVG9DZW50cyAvIDEwMDsKICAgICAgZWxzZQogICAgICAgIHJvdW5kZWRWYWx1ZSArPSBtb2RUb0NlbnRzIC8gMTAwOwoKICAgICAgcmV0dXJuIHJvdW5kZWRWYWx1ZTsKICAgIH0KfQ==