Home > Net >  Rounding a number away from zero in c#
Rounding a number away from zero in c#

Time:06-22

In my database, I have three point floating numbers columns and a process that multiplies the two first ones to get the third one value

item.ValorTotal = Math.Round(item.Qtde * item.ValorUnitario, 2, MidpointRounding.AwayFromZero);

but if my item.Qtde is like 0.03 and my item.ValorUnitario is 0.02, item.ValorTotal the result is 0.0006 and the variable receives zero because of the round, how do I can round to get 0.01 and continue using two numbers after decimal point?

In short I do like to round to the first possible number (0.01) when I receive a lower number like 0.006 or 0.0006

CodePudding user response:

Instead of Math.Round() you can use Math.Ceiling().

The Math.Ceiling() method in C# is used to return the smallest integral value greater than or equal to the specified number.

So in your code example it will be something like:

item.ValorTotal = (Math.Ceiling((item.Qtde * item.ValorUnitario) * 100) / 100);

Output:

0,0006 => 0,01
0,0106 => 0,02

CodePudding user response:

AwayFromZero doesn't mean that you always round upward. In real it works at most values like usual rounding. As far as I understood it only has an effect if you would round 0.005x. Therefore write

item.ValorTotal = Math.Round(item.Qtde * item.ValorUnitario   0.005, 2, MidpointRounding.AwayFromZero);

when you want to round upward and both values are positive.

  • Related