基于格式字符串标识小数位数 [英] identify the number of decimal places based on the format string

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

问题描述

我需要根据#。00 格式字符串确定小数位数,应返回 2

I have a requirement to identify the number of decimal places based on the format string like #.00 should return 2.

###,#.  === > 0 
###,#.00000 ===> 4

有没有更好的方法,只是循环通过字符,并检查他们的索引是否大于点和递增计数...

Is there a better way than just looping through the characters and checking if their index greater than dot and incrementing a count...

推荐答案

如果您可以假设输入在十进制后只有零,从IndexOf(。)的字符串的长度。

If you can assume that the input will only have zeros after the decimal, you could subtract the string's Length from the IndexOf(".").

(str.Length - str.IndexOf('.') - 1)

否则,你必须在十进制之后计零。我个人使用LINQ语句。

Otherwise, you'll have to count zeros after the decimal. I'd personally use a LINQ statement. It won't be any more performant, but it'll look nicer.

str.SkipWhile(c => c != '.').Count(c => c == '0')

,还有其他警告。要想出一个正确的答案,您必须提供更多关于如何处理这种情况的信息:

Of course, there are other caveats. To come up with a "correct" answer, you'll have to provide more information about how you want to handle cases like this:

(12345.4321).ToString("#.##") // 12345.43
(12345.4321).ToString("#.#####") // 12345.4321
(12345.4321).ToString("#.#####-0") // 12345.43210-0

需要计算哈希值,因为他们可能会导致额外的小数位出现,或不计数,因为他们可能不会?

So do you need to count hashes because they could cause an extra decimal place to appear, or not count them because they might not?

这篇关于基于格式字符串标识小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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