我正在开发一个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.
答案 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
}