What is the alternative for Math.Round(decValue, 2, MidpointRounding.AwayFromZero)

for example in C#

using System;

public class Example
{
   public static void Main()
   {
      Single value = 16.325f;
      Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ", 
                        value, value.GetType().Name, (double) value, 
                        ((double) (value)).GetType().Name);
      Console.WriteLine(Math.Round(value, 2));
      Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero));
      Console.WriteLine();
      
      Decimal decValue = (decimal) value;
      Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ", 
                        value, value.GetType().Name, decValue, 
                        decValue.GetType().Name);
      Console.WriteLine(Math.Round(decValue, 2));
      Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero));
   }
}
// The example displays the following output:
//    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
//    16.33
//    16.33
//    
//    Cast of 16.325 (type Single) to 16.325 (type Decimal):
//    16.32
//    16.33

My test:

var jsonData = pm.response.json();


pm.test('Response body has accurate rebate value', function() {
    var expectedValue = JSON.parse(postman.getGlobalVariable('value')/100)*(16.706);
    Values = (jsonData.calculationResultList[0].totalAdjustment.value);

pm.expect(Values).to.eql(expectedValue);

Output I got:    
FAIL| AssertionError: expected -37.62 to deeply equal -37.6152296
    

So I tried,

let Rebate = Math.round(expectedValue, 2);
pm.expect(Values).to.eql(Rebate);

Output:    
FAIL| AssertionError: expected -37.62 to deeply equal -38

could I suggest a bit of a different approach…?
pm.expect(Math.abs(expectedValue-value)).to.be.lt(0.01);

Hi @VincentD123,

Thank you for your solution.

It was’t exactly what i was looking for but it’s a workaround for now.

Found this gem by Jack Moore
https://www.jacklmoore.com/notes/rounding-in-javascript/

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

var value = -37.6152296;

var expectedValue = round(value, 2);

pm.expect(-37.62).to.eql(expectedValue);

@aschultz,

Thank you.

1 Like