5

How do I round a decimal to the nearest 0.05 cents in c#?

e.g $3.44 to be rounded to $3.45 or $3.48 to $3.50

I played around with math.round() though havent figured this out.

peterh
  • 1
  • 15
  • 76
  • 99
SKM
  • 53
  • 1
  • 1
  • 5

3 Answers3

25

This has been asked many times before

Try Math.Round(val*20)/20

See round 0.05

Community
  • 1
  • 1
Adriaan Stander
  • 156,697
  • 29
  • 278
  • 282
6

Here are a couple of methods I wrote that will always round up or down to any value.

        public static Double RoundUpToNearest(Double passednumber, Double roundto)
    {

        // 105.5 up to nearest 1 = 106
        // 105.5 up to nearest 10 = 110
        // 105.5 up to nearest 7 = 112
        // 105.5 up to nearest 100 = 200
        // 105.5 up to nearest 0.2 = 105.6
        // 105.5 up to nearest 0.3 = 105.6

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Ceiling(passednumber / roundto) * roundto;
        }
    }
    public static Double RoundDownToNearest(Double passednumber, Double roundto)
    {

        // 105.5 down to nearest 1 = 105
        // 105.5 down to nearest 10 = 100
        // 105.5 down to nearest 7 = 105
        // 105.5 down to nearest 100 = 100
        // 105.5 down to nearest 0.2 = 105.4
        // 105.5 down to nearest 0.3 = 105.3

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Floor(passednumber / roundto) * roundto;
        }
    }
NER1808
  • 1,679
  • 1
  • 28
  • 42
  • I guess just round to nearest will be useful too. you can use both of your methods and then check which of Math.Abs(result) is closer to your number – user7313094 Jun 07 '19 at 08:48
0

This snippet only round up to the nearest 0.05

    public static decimal Round(decimal value) {
        var ceiling = Math.Ceiling(value * 20);
        if (ceiling == 0) {
            return 0;
        }
        return ceiling / 20;
    }
Madu Alikor
  • 2,416
  • 3
  • 18
  • 35