rounding with specific decimals c #

2

Hi, I would like to see if you can help me. I want to round a value with 2 decimals but at a point value.

for example, if the decimal value is between 0 and 0.49, it remains at 0.50 if the decimal value is between 0.51 and 0.99 goes to the next integer with decimal 00.

thank you very much

    
asked by Pablo 17.09.2018 в 21:19
source

2 answers

4

You must use the function Math.Ceiling in the following way if you want to round up in values of 0.5:

var resultado = Math.Ceiling(valor * 2) / 2;

Or also:

var resultado = Math.Ceiling(0.22 / 0.5) * 0.5;

If for example you want to round up to the next value closer to 0.05, it would be like this:

var resultado = Math.Ceiling(valor * 20) / 20;
// o
var resultado = Math.Ceiling(0.22 / 0.05) * 0.05;

Generalizing:

private double RedondeoArriba (double valor, double paso)
{
     return Math.Ceiling(valor/ paso) * paso;
}
    
answered by 18.09.2018 в 08:57
-1

Use the Math.Round ()

method

With this you can round a value of type Double or Decimal

Example:

using System;

public class Sample {
   static void Main() {
      Console.WriteLine(Math.Round(3.44m, 1)); 
      Console.WriteLine(Math.Round(3.45m, 1)); 
      Console.WriteLine(Math.Round(3.46m, 1)); 
      Console.WriteLine();

      Console.WriteLine(Math.Round(4.34m, 1)); 
      Console.WriteLine(Math.Round(4.35m, 1)); 
      Console.WriteLine(Math.Round(4.36m, 1)); 
   }
}
// The example displays the following output:
//       3.4
//       3.4
//       3.5
//       
//       4.3
//       4.4
//       4.4
    
answered by 17.09.2018 в 21:30