什么是确定的格式字符串的小数位数的好方法? [英] What would be a good way of determining number of decimal places from a format string?

查看:177
本文介绍了什么是确定的格式字符串的小数位数的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个函数,如下所示:

I'd like a function that looks like this:

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

的投入将是完全一样的,可依法传递给负责格式化数字,例如, double.ToString 十进制方法的ToString

将输出一个 INT 表示最低数量由格式字符串所需的小数位。

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

因此​​,这里有几个例子输入/输出我希望(我们只能说离开 formatProvider 结果在目前的文化正在使用):

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

如果可能的话,我想这样做的正确的方式;即,没有黑客。但是,如果黑客必须这样,我也要AP preciate的的黑客的建议;)

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,并格式化,然后解析字符串来算的小数位数。我想这有资格作为一个黑客,但它应该工作pretty的可靠。

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.

这篇关于什么是确定的格式字符串的小数位数的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆