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

寵の児 提交于 2019-12-11 10:35:26

问题


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 ;)


回答1:


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.




回答2:


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???



来源:https://stackoverflow.com/questions/4089661/what-would-be-a-good-way-of-determining-number-of-decimal-places-from-a-format-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!