我需要一个函数来解析用户输入的数字为双精度。我不能在客户端做任何事情,也不能改变输入的方式。
Input | Desired Output
"9" | 9
"9 3/4" | 9.75
" 9 1/ 2 " | 9.5
"9 .25" | 9.25
"9,000 1/3" | 9000.33
"1/4" | .25我看到了这个post,但它使用的是Python,我只是想知道在我花时间编写自己的C#之前,是否有人知道任何奇特的Python处理方法。
发布于 2012-01-07 03:12:02
以下是我最终使用的内容:
private double ParseDoubleFromString(string num)
{
//removes multiple spces between characters, cammas, and leading/trailing whitespace
num = Regex.Replace(num.Replace(",", ""), @"\s+", " ").Trim();
double d = 0;
int whole = 0;
double numerator;
double denominator;
//is there a fraction?
if (num.Contains("/"))
{
//is there a space?
if (num.Contains(" "))
{
//seperate the integer and fraction
int firstspace = num.IndexOf(" ");
string fraction = num.Substring(firstspace, num.Length - firstspace);
//set the integer
whole = int.Parse(num.Substring(0, firstspace));
//set the numerator and denominator
numerator = double.Parse(fraction.Split("/".ToCharArray())[0]);
denominator = double.Parse(fraction.Split("/".ToCharArray())[1]);
}
else
{
//set the numerator and denominator
numerator = double.Parse(num.Split("/".ToCharArray())[0]);
denominator = double.Parse(num.Split("/".ToCharArray())[1]);
}
//is it a valid fraction?
if (denominator != 0)
{
d = whole + (numerator / denominator);
}
}
else
{
//parse the whole thing
d = double.Parse(num.Replace(" ", ""));
}
return d;
}发布于 2012-01-07 01:13:18
BCL中没有内置的东西可以做到这一点,但是有很多现有的mathematical expression parsers可以做到这一点(尽管对于这种特定的情况,这可能有些过头了)。
自己写一个,对于你发布的有限的用例来说应该不难。
发布于 2012-01-07 01:16:08
我看到两个部分。第一个空格之前的所有内容都是完整的部分。第一个空格之后的所有内容都是小数部分。在将两个部分分开之后,您只需从小数部分中剥离空格,在/字符上拆分该部分,然后将第一部分除以第二部分(如果有第二部分)。然后将结果添加到积分部分以找到您的答案。
这个算法应该会为你的每个样本提供一个正确的结果。对于“9.25/4”或“9.3/0”这样的示例,它也可能给出不正确的结果,所以这些都是需要注意的东西。其他内容包括前导空格,是否允许其他空格,货币符号,"9.25“(没有空格)是否为有效输入,以及如何处理"1/3”、"1/10“(二进制中的无理)等无理分数。
我通常不太相信静态类型语言的测试驱动设计(应该先编写测试,然后实现100%的覆盖率),但我确实认为单元测试在某些特定的情况下是有价值的,这就是其中之一。我会为一些常见的和边缘的情况做一些测试,这样你就可以确定你最终得到的任何东西都能正确地处理输入以通过测试。
https://stackoverflow.com/questions/8761531
复制相似问题