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.
Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.)
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.
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.
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).
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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With