CO2 Software
CO2 Software

Reputation: 55

Rounding decimals to nearest 5th c#

I'm currently trying to calculate an exact number from a formula, but am having trouble converting decimal components of a whole number,

For example, if I divide 10 by 3 I'll have 3.3333, My calculation would need to be from 3.2. If I had 6.5, My calculation would need to be off 6.4.

Where I'm struggling is catching the decimal of this moving number, then rounding only the decimal part of that number. Some example of my code is below

// This number should be rounded down to the nearest .2
TopCalc = (In - UpperThreshold) * (TopPerc / 100);

// This number should be rounded down to the nearest .2
MidCalc = (UpperThreshold - LowerThreshold) * (MidPerc / 100);

// This number should be rounded down to the nearest .2
LowCalc = LowerThreshold * (LowPerc / 100);

decimal Total = TopCalc + MidCalc + LowCalc;

return Total;

So breaking it down further, lets say each 0.2 is a 20Cents/Pence coin, 90 % of a coin is not legal tender, so in a situation of you having to give $/£120.36 and all you have for change is 20 cents/pence pieces, you would only give $/£120.20 as the 16Cents/Pence does not make up a whole coin in this example. Some more examples are below

1.235 = 1.2
1.599 = 1.4
1.611 = 1.6
1.799999999999 = 1.6
1.85 = 1.8

Always rounding down to the nearest literal 0.2 never rounding up.

Upvotes: 0

Views: 253

Answers (2)

Keith Nicholas
Keith Nicholas

Reputation: 44298

you can use something like

static decimal NthRound(decimal d, decimal nth)
{
    var intPart = decimal.Truncate(d);
    var fifth = decimal.Truncate(nth * (d - intPart)) / nth;
    return intPart + fifth ;           
}

and then

Console.WriteLine( NthRound(10M/2M, 5M));
Console.WriteLine( NthRound(10M/3M, 5M));
Console.WriteLine( NthRound(13M/2M, 5M));

which gets

enter image description here

which rounds down to the nearest 5th in this case

Upvotes: 2

Deolus
Deolus

Reputation: 317

Are your decimals always positive, or can they be negative?

I managed to get this to work, but it's not very elegant. There may be a better solution:

    decimal d = 2.235M;
    int i;

    d = Math.Round(d, 1);
    i = (int) (d*10);
    i = i >> 1;
    i = i << 1;
    d = (decimal) i/10;

Upvotes: 1

Related Questions