从格式字符串确定小数位数的好方法是什么?
我想要一个如下所示的函数:
int GetDecimalPlaces(string format, IFormatProvider formatProvider = null);
输入与可以合法传递给负责格式化数字的方法的输入完全相同,例如,double.ToString
、decimal。 ToString
。
输出将是一个 int
,指示格式字符串所需的最低小数位数。
因此,这里有几个我期望的输入/输出示例(假设将 formatProvider
保留为 null
会导致使用当前区域性):
Input | Output ------|------- N2 | 2 0 | 0 0.000 | 3 g | 0 0.0## | 1
如果可能,我会喜欢以“正确”的方式做到这一点;即,无需黑客。但如果我必须破解,我也会感激好的黑客建议;)
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 ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法可能是获取一个整数,例如 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.
为什么不转换为字符串,然后搜索分隔符位置。从字符串的长度中减去该值。
再次可能是黑客攻击,但是???
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???