用逗号和点接受小数点数

时间:2017-03-30 14:04:43

标签: c# uwp

我正在开发一个uwp app,我有一个文本框,我只想接受小数,逗号或点(例如:1.5或1.5或1.50或1.50) 使用在此文本框中输入的值,并在单击应用程序中的按钮后将执行操作:

double value= Convert.ToDouble(inputBox.Text);

InputBox是我的文本框,用户输入数字。 如果我输入例如1,50不给出错误,并执行我想要的操作。如果我输入1.50,则会在我提供的代码行中出现此错误:

System.FormatException was unhandled by user code
Message=Input string was not in a correct format.

1 个答案:

答案 0 :(得分:6)

您可以手动指定分隔符(., 并尝试使用以下两种格式进行分析:

string source = "123,456"; // "123.456" (with dot) will be accepted as well
double result;

if (double.TryParse(source, 
                    NumberStyles.Number, //TODO: you may want to change style
                    new NumberFormatInfo() { 
                      NumberDecimalSeparator = ".", 
                      NumberGroupSeparator = "" }, 
                    out result) ||
    double.TryParse(source, 
                    NumberStyles.Number, //TODO: you may want to change style
                    new NumberFormatInfo() { 
                      NumberDecimalSeparator = ",", 
                      NumberGroupSeparator = "" }, 
                    out result)) 
{
    // result contains parsed source value
}
else 
{
    // source is not a valid double
}