Dan Tao
Dan Tao

Reputation: 128317

What would be a good way of determining number of decimal places from a format string?

I'd like a function that looks like this:

int GetDecimalPlaces(string format, IFormatProvider formatProvider = null);

The inputs would be exactly the same as those which can be legally passed to methods responsible for formatting numbers, e.g., double.ToString, decimal.ToString.

The output would be an int indicating the lowest number of decimal places required by the format string.

So here are a couple of example inputs/outputs I would expect (let's just say leaving formatProvider as null results in the current culture being used):

Input | Output
------|-------
N2    | 2
0     | 0
0.000 | 3
g     | 0
0.0## | 1

If possible, I'd like to do this the "right" way; i.e., without hacks. But if hack I must, I would also appreciate good hacking suggestions ;)

Upvotes: 1

Views: 109

Answers (2)

DaveM
DaveM

Reputation: 734

Why not convert to a string, then search for the separator character location. subtract this value from the length of the string. Again possible a hack but???

Upvotes: 0

o. nate
o. nate

Reputation: 384

Probably the easiest way would be to take a whole number, like 1, and format it, then parse the string to count the number of decimal places. I guess this qualifies as a hack, but it should work pretty reliably.

Upvotes: 1

Related Questions