Always Round UP a value in C#

Thilina Nakkawita picture Thilina Nakkawita · Feb 6, 2014 · Viewed 12.5k times · Source

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.

Answer

dcastro picture dcastro · Feb 6, 2014

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