Domanda

I'm trying to come up with a global way of converting a string to X number of decimal places and I'm having no luck. I need this to return a decimal with X number of decimals.

Here is what I have so far but I cannot figure out how to get it to know what to divide by easily:

public static decimal ToXDecimalPlaces(this object value, int numberofdecimalplaces, decimal defaultValue = 0)
{
  double retval;
  if (double.TryParse(value.ToString(), out retval))
  {
    return (decimal)(retval / 10);
  }
  return defaultValue;
}

So if I send it:

value = "12345"
value.ToXDecimalPlaces(2) 

I'd like to get back:

123.45

etc.

The division of the retval needs to be different pending on the numberofdecimalplaces.

Any suggestions? I would prefer not to have to create a handful of extension methods or is that what I should do?

Should I just create:

To1DecimalPlaces
To2DecimalPlaces
To3DecimalPlaces
etc

For each one I need and move on?

È stato utile?

Soluzione

How about using Math.Pow?

Something like

return (decimal)(retval / Math.Pow(10, numberofdecimalplaces));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top