Always Round UP a value in C#

12,265

Solution 1

Finally I come up with a solution. I improved Sinatr's answer as below,

var value = 2.524;
var result = RoundUpValue(value, 2); // Answer is 2.53

public double RoundUpValue(double value, int decimalpoint)
{
    var result = Math.Round(value, decimalpoint);
    if (result < value)
    {
        result += Math.Pow(10, -decimalpoint);
    }
    return result;
}

Solution 2

As Jon said, use a decimal instead. Then you can do this to always round up with 2 decimal points.

Math.Ceiling(value2 * 100) / 100

Solution 3

var value2 = 2.524;
var result2 = Math.Round(value2, 2); //Expected: 2.53 //Actual: 2.52
if(result2 < value2)
    result += 0.01; // actual 2.53

Solution 4

What about this:

Math.Round(Value+0.005,2)
Share:
12,265
Thilina Nakkawita
Author by

Thilina Nakkawita

With more than 8 years of experience, an expert in C#, ASP .NET &amp; MVC, and SQL Server with database analysis and design. Skilled in developing business plans, requirements specifications, user documentation, and architectural systems research.

Updated on July 23, 2022

Comments

  • Thilina Nakkawita
    Thilina Nakkawita almost 2 years

    I want to roundup value according to the 3rd decimal point. It should always take the UP value and round. I used Math.Round, but it is not producing a result as i expected.

    Scenario 1

    var value1 = 2.526;
    var result1 = Math.Round(value1, 2); //Expected: 2.53 //Actual: 2.53
    

    Scenario 2

    var value2 = 2.524;
    var result2 = Math.Round(value2, 2); //Expected: 2.53 //Actual: 2.52
    

    Scenario 1 is ok. It is producing the result as i expected. In the 2nd scenario I have amount as 2.522. I want to consider 3rd decimal point (which is '4' in that case) and it should round UP. Expected result is 2.53

    No matter what the 3rd decimal point is (whether it is less than 5 or greater than 5), it should always round UP.

    Can anyone provide me a solution? I don't think Math.Round is helping me here.