10

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
Dumi
  • 1,414
  • 4
  • 21
  • 41
  • 3
    If you're interested in decimal points, perhaps you should be using the `decimal` type rather than `double`? What kind of value are you trying to represent? – Jon Skeet Feb 06 '14 at 09:46
  • 2
    "but it is not producing a result as i expected." - to be honest, "always round UP" is not a result that many people expect. – Marc Gravell Feb 06 '14 at 09:47
  • Also worth pointing out that Math.Round is commonly misunderstood: http://stackoverflow.com/questions/977796/why-does-math-round2-5-return-2-instead-of-3-in-c – Jordan Feb 06 '14 at 09:47

4 Answers4

14

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
dcastro
  • 66,540
  • 21
  • 145
  • 155
6

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;
}
Dumi
  • 1,414
  • 4
  • 21
  • 41
5
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
Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • This is correct according to the question i asked (round up value comparing 3rd decimal point). – Dumi Feb 07 '14 at 17:04
1

What about this:

Math.Round(Value+0.005,2)
Trifon
  • 1,081
  • 9
  • 19
  • Note that you need to force mid-point rounding DOWN when doing this, otherwise a 0.000 could go *upwards*; and there is no "down" `MidpointRounding` mode... – Marc Gravell Feb 06 '14 at 09:49
  • 3
    @SonerGönül it's a pretty common trick; the ceiling version is better, though – Marc Gravell Feb 06 '14 at 09:49
  • looks like rounding to 2dp and always rounding up 3rd dp if 3rd dp > 0. Although that probably should be Value+0.005-EPSILON? O.o. – Meirion Hughes Feb 06 '14 at 09:50