You have two problems with your code. The first is that the adopted pattern of rounding is the same. If you want to change you have to configure it with the MidpointRounding
.
But in this case it still will not give the expected result because it is using a double
type that is not accurate, so the number is a little less than 1190.245, which would still cause it to round down. If you want accuracy you should use decimal
.
Here I show you that it works by configuring midpoint , as long as the value is really accurate or slightly above, but it still will not work if it is a little below what you see. And I'll show you that if you use a decimal it works at the number you want.
Do not use binary floating-point types if you want accuracy . Most of the financial software I see has this bug causing damage to its users.
The second example is with the correct and visible result. Even if you use decimal
and setting up the midpoint will still give you the same result. If you want other things you need to define a criterion and decide what to do, that's normal.
using System;
using static System.Console;
using static System.Math;
public class Program {
public static void Main() {
WriteLine(Round(1190.205, 2, MidpointRounding.AwayFromZero));
WriteLine(Round(1190.245M, 2, MidpointRounding.AwayFromZero));
}
}
See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .