C# 整数末尾带有特定字符的字符串
我可以通过查看字符串的最后一个字符并根据它的内容将其发送到特定函数以进行转换,通过一系列步骤来完成此操作。但我只是想知道是否有更简单的方法来执行以下操作。
例如,我有一个字符串可能会表示 23.44M 或 5.23B 之类的内容,M 和 B 显然代表“Million”或“Billion”,我想将该字符串转换为它所代表的数字,但只是不确定最有效的方法来做到这一点。寻找一些想法。谢谢
I could probably do this in a series of steps by looking at the last character of the string and based on what it is send it to a particular function to have the conversion made. But I am just wondering if there is any easier way to do the following.
For example I have a string that might say something like 23.44M or 5.23B, the M and B obviously stand for "Million" or "Billion", I want to convert that string into the number it is representing but just not sure of the most efficient way to do this. Looking for some ideas. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我将构建一个字典,并用键值对填充它,例如 (B, 1,000,000,000) 和 (M, 1,000,000)。取出末尾的字符,查找该字符的值,然后相乘。
I would build a Dictionary, and populate it with key value pairs such as (B, 1,000,000,000) and (M, 1,000,000). Take the character off the end, look up the value for that character, and multiply.
这些方面的东西对你有用吗?
如果输入的格式可能有所不同,则必须添加额外的逻辑,包括防止非法 Parse()。
Something along these lines work for you?
If the format of your input can vary, you would have to add additional logic, including protecting against an illegal Parse().
作为 @Smelch 答案的书呆子替代方案,您可以填充字符串常量 POSTFIXES,例如“xHKxxMxxBxxTxxQ”,并将基数乘以 Math.Pow(10,POSTFIXES.LastIndexOf(...)+1)
As a nerdy alternative to the answer by @Smelch you could populate a String constant POSTFIXES, such as "xHKxxMxxBxxTxxQ" and multiply your base by Math.Pow(10,POSTFIXES.LastIndexOf(...)+1)
您最好的选择可能是使用正则表达式(MSDN 文档此处)可以分组(这不是正则表达式语法)[numbers][char]
那么你有 2 个组,第一个是你的数字,第二个是你的“因子”字符
,然后用
double.TryParse()
转换第一个组,并通过 switch 或 a 运行第二个组一组if
语句,根据需要相乘以获得最终结果。your best bet is probably to use a regex (MSDN docs here) you could group on (this is NOT regex syntax) [numbers][char]
then you have 2 groups, the first would be your number, the second would be your "factor" character
then, convert the first with
double.TryParse()
, and run your second through a switch or a set ofif
statements to multiply as needed to get your end result.使用字典将字符映射到乘数而不是 switch 语句并仅使用大写字母:
Use a dictionary to map chars to multipliers instead of a switch statement and use upper case only: