Two ways to display decimal

let's say I have a list of decimals:

List<decimal> values; 

and 2 to display the decimal:

 string DisplayPct(decimal pct) { return pct.ToString("0.00 %"); } string DisplayValue(decimal val) { return val.ToString("0.00"); } 

What would be the best mechanism to implement so that I can know which function to call depending on the value?

I would like to have, for example, typedefs in C #. That way, I could declare a Percent type and a Decimal type, which both would represent decimal values, but then I could know how to display a value based on its type.

Any equivalent in c #?

thanks

+2
source share
3 answers

Replace the percentage in the class. A bit of work on your part. Just remember to define an implicit operator to write decimals, as well as some other operations and ToString as needed.

+2
source

Here are my classes:

  public class Percent { public decimal value; public Percent(decimal d) { value = d; } public static implicit operator Percent(decimal d) { return new Percent(d); } public static implicit operator decimal(Percent p) { return p.value; } } public class DecimalPrecise { public decimal value; public DecimalPrecise(decimal d) { value = d; } public static implicit operator DecimalPrecise(decimal d) { return new DecimalPrecise(d); } public static implicit operator decimal(DecimalPrecise d) { return d.value; } } 
+3
source

It looks like you want two classes: decimal and percentage. Each of them will have a ToString, which prints accordingly. If they both have the same interface, you can have a collection of both on the list using this common interface.

+2
source

All Articles