Rounding a Number Using Custom Rules

Consider the following C # code:

Decimal number = new decimal(8.0549);
Decimal rounded = Math.Round(number, 2);
Console.WriteLine("rounded value: {0}", rounded);

will produce the result: 8.05

Math.Round algoritm only checks the next digit after the decimal number taken as a parameter.
I need an algorithm that checks the entire decimal string. In this case, 9 must have rounds 4-5, which, in turn, will be rounded from 5 to 6, which will give the final result 8.06

Additional examples:
8.0545 → 8.06
8.0544 → 8.05

Is there a built-in method that can help me?
Thank.

+3
source share
2 answers

No; you will need to write it yourself.

+1

, , ;)

, , , - :

    private static double NotQuiteRounding(double numToRound, int maxPlaces, int minPlaces) 
{ 
    int i = maxPlaces;
    do
    { 
        numToRound = Math.Round(numToRound,i); 
        i = i - 1;
    } 
    while (i >= minPlaces);

    return numToRound; 
} 

:

    Console.WriteLine(NotQuiteRounding(8.0545,10,2));
    Console.WriteLine(NotQuiteRounding(8.0544,10,2));
+1

Source: https://habr.com/ru/post/1772366/


All Articles