Vikas Sardana
Vikas Sardana

Reputation: 1643

Round off Decimal at application level in C#

In our application there are around 200 decimal variables,Is there any way which we can round off decimal to 2 places before assignment.

Or any application level config to achieve this

Currently we are try to achieve using Extension method below

public static decimal RoundOff(this decimal value)
{
   return Math.Round(value,2);
}

Upvotes: 0

Views: 296

Answers (3)

InBetween
InBetween

Reputation: 32790

It depends. If calculation correctness depends on the variables being rounded previously then just formatting the output is not an option. You could keep using your extension method on every assignment but that is potentially error prone (you can miss one) or you can create a wrapper class:

public struct RoundedDecimal: IEquatable<RoundedDecimal>, IFormattable, IComparable<RoundedDecimal>
{
     private readonly decimal value;

     public RoundedDecimal(decimal value)
     {
          this.value = Math.Round(value, 2);
     }

     public static implicit operator RoundedDecimal(decimal value) =>
        new RoundedDecimal(value);

     public static explicit operator Decimal(RoundedDecimal value) =>
         value;

     public static RoundedDecimal operator *(RoundedDecimal left, RoundedDecimal right) =>
         new RoundedDecimal(left.value * right.value);

     //and so on
 }

Upvotes: 2

zdimension
zdimension

Reputation: 1084

Well, if you want every decimal to be rounded to two decimals, you could (veeeery ugly) make your own number struct with implicit operators for casting from and to decimal that round to two decimals. This way, when you write a decimal constant in your code and that it is passed to a function or field expecting , or vice-versa, it'll be automatically rounded at two decimals. But it's still better and cleaner to continue using your extension method.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

No, there is no way to control number of decimal places stored in values of decimal type.

You can either round values via code as you do now, or maybe just output values with 2 decimal points (c# - How do I round a decimal value to 2 decimal places (for output on a page))

Upvotes: 3

Related Questions