【发布时间】:2019-09-02 08:01:23
【问题描述】:
我有这么一小段代码:
using System;
using System.Globalization;
namespace project
{
class conditionalStatements
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number greater than 45.2");
string answer = Console.ReadLine();
decimal answer_decimal = Convert.ToDecimal(answer);
// decimal answer_decimal = Decimal.Parse(answer);
decimal compareValue = 45.2m;
Console.WriteLine(answer_decimal);
//prints 452
if(Decimal.Compare(answer_decimal, compareValue) > 0){
// stuff
}
else{
// should enter here
}
}
}
}
问题在于,由于Convert.ToDecimal() 和Decimal.Parse() 方法都忽略了十进制值的点表示法(或者至少这是发生在我身上的事情),所以数字被解释为452 而不是45.2。无论我输入多少点。事实上,如果我要进入:
45......2
转换后的值仍将转换为452。 仅当我使用逗号时,转换后的数字会被正确解释为45.2,并且我可以输入else 条件。
我没有更改NumberFormatInfo.CurrencyDecimalSeparator。我将其保留为默认值'.'
【问题讨论】:
-
线程与什么文化相关联?
-
与您当前问题无关的建议。切勿尝试在用户输入上使用 Convert.ToXXXX。如果用户键入无效数字,您的代码将引发异常。在这些情况下,请始终使用 decimal.TryParse
标签: c# .net parsing decimal decimal-point