Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always Round UP a value in C#

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.

like image 839
Thilina Nakkawita Avatar asked Feb 06 '14 09:02

Thilina Nakkawita


People also ask

Does C automatically round up or down?

Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.)

What is roundUp in C?

The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument.

How do I use ceil C?

The ceil() function takes a single argument and returns a value of type int . For example: If 2.3 is passed to ceil(), it will return 3. The function is defined in <math. h> header file.

Does round Down in C?

In the C Programming Language, the floor function returns the largest integer that is smaller than or equal to x (ie: rounds downs the nearest integer).


3 Answers

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;
}
like image 109
Thilina Nakkawita Avatar answered Oct 17 '22 01:10

Thilina Nakkawita


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
like image 27
Sinatr Avatar answered Oct 17 '22 01:10

Sinatr


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
like image 12
dcastro Avatar answered Oct 17 '22 00:10

dcastro