0

Math.Round() will always return results according to mathematics rules.

For Example 0.124 will be rounded off to 0.12 if done for 2 places of decimal.

Can I make it to always give me next higher value, for example 0.124 Rounded off to 2 places of decimal should give 0.13 and likewise?

5 Answers5

1

You could use Math.Ceiling as mentioned by Baszz. You need to multiply and divide by some factor to mimic the rounding behaviour:

 var decimals = 2;
 var fac = Math.Pow(10, decimals);
 var result = ((int)Math.Ceiling(0.124 * fac)) / fac;

 Console.WriteLine(result);
faester
  • 14,886
  • 5
  • 45
  • 56
1

Try this:

var input = 0.124;
var decimals = 2;
var r = (input == Math.Round(input, decimals)) ? 
    Math.Round(input, decimals) : 
    Math.Round(input + Math.Pow(10, -decimals), decimals);

You could create an extension method:

public static double RoundUp(this double input, int decimals)
{
    return  (input == Math.Round(input, decimals)) ?
        Math.Round(input, decimals) :
        Math.Round(input + Math.Pow(10, -decimals), decimals);
}

and use it like:

double input = 0.1224;
var decimals = 3;
var r = input.RoundUp(decimals);
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
0

I think you should take a look at the Math.Ceiling() method:

http://msdn.microsoft.com/en-us/library/zx4t0t48(v=vs.110).aspx

Look at this post on SO where it is explained how to use it:

How to round a decimal up?

Community
  • 1
  • 1
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
  • That only rounds to integers though doesn't it? yes, it might help but this isn't really a complete answer. Especially because it is not much more than a link answer. – Chris Nov 19 '13 at 09:29
0

for this, you try math.ceiling() instead of using math.round()..!

       Math.Round() --> Rounding values  
       Math.Ceiling()  --> Next higher value
       Math.Floor() --> Next lower value
Vigna
  • 113
  • 1
  • 5
  • 13
0

Here you go, example for Math.Ceiling() concept

   using System;

     class Program
         {
         static void Main()
         {
     // Get ceiling of double value.
      double value1 = 123.456;
      double ceiling1 = Math.Ceiling(value1);

    // Get ceiling of decimal value.
      decimal value2 = 456.789M;
      decimal ceiling2 = Math.Ceiling(value2);

    // Get ceiling of negative value.
      double value3 = -100.5;
      double ceiling3 = Math.Ceiling(value3);

    // Write values.
      Console.WriteLine(value1);
      Console.WriteLine(ceiling1);
      Console.WriteLine(value2);
      Console.WriteLine(ceiling2);
      Console.WriteLine(value3);
      Console.WriteLine(ceiling3);
      }
    }

Output
******

123.456
124
456.789
457
-100.5
-100
Vigna
  • 113
  • 1
  • 5
  • 13