Decimal rounding issues

I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two. Let's say the code is as follows:

var anone    = "23"
var antwo    = "23.0"
var anthree  = "23.467"
var anfour   = "23.125"

In order to remove the leading decimal and zero I have used the following method:

 var removingzero = antwo.Replace(".0", "");
 // The result will be = 23

In order to round off and limit the number to two decimal points I have used the following method:

 var convertodecimal = Decimal.Parse(anthree);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.47

similarly in order to convert the last one I follow the same method:

 var convertodecimal = Decimal.Parse(anfour);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.12
 // But the Result should be = 23.13

So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.

Upvotes: 0

Views: 228

Answers (2)

Ashu_90
Ashu_90

Reputation: 934

Try by changing your Math.Round() to below one:

Math.Round(num,2, MidpointRounding.AwayFromZero)

Upvotes: 1

Rufus L
Rufus L

Reputation: 37020

It sounds like your question is a long way of asking "How can I force rounding UP when a decimal number ends in 5?"

If that's the case, then you can use the overload of Math.Round that takes a MidpointRounding argument, and specify either MidpointRounding.AwayFromZero or MidpointRounding.ToPositiveInfinity.

The behavior of these is the same for positive numbers, but difference is seen with negative numbers, where -23.125 will round to -23.13 if AwayFromZero is specified, or -23.12 if ToPositiveInfinity is specified.

So your code might look like this instead:

var roundtotwo = Math.Round(convertodecimal, 2, MidpointRounding.AwayFromZero);

Upvotes: 1

Related Questions