将字符串解析为十进制适用于 Windows 8 但不适用于 windows 7
Parsing a string to decimal works on Windows 8 but not on windows 7
我有一个方法可以获取字符串值并将其解析为十进制。这在 windows 8.1 上完美运行,但是当我在 windows 7 上测试应用程序时,它失败了。
Windows 7 确实安装了 Dot net Framework 4.5。
可能是什么问题?
方法如下:
void Save_Details()
{
//The customer enters dots instead of commas to specify a decimal place
string Ammount_Now = textbox1.Text.Replace('.', ',');//value text entered is 123.34
//The value of Ammount_Now is now 123,34
decimal value = 0;
bool Ammount_Good = decimal.TryParse(Ammount_Now, out value);
if(Ammount_Good)
{
//continue with method
// windows 8 returns true in the decimal.TryParse()
// windows 7 returns false in the decimal.TryParse()
// They both use .net framework 4.5
}
else
{
//failed parsing
}
}
OS 版本没有问题,您在不同语言环境的机器上测试了代码。
只要您在解析时使用正确的 CultureInfo,也无需将小数点替换为 "fix"。如果输入文本总是希望使用 .
作为小数点,你应该使用 Decimal.TryParse Method (String, NumberStyles, IFormatProvider, Decimal) 重载:
decimal.TryParse(Amount_Now,NumberStyles.Number,CultureInfo.InvariantCulture,out value)
我有一个方法可以获取字符串值并将其解析为十进制。这在 windows 8.1 上完美运行,但是当我在 windows 7 上测试应用程序时,它失败了。 Windows 7 确实安装了 Dot net Framework 4.5。
可能是什么问题?
方法如下:
void Save_Details()
{
//The customer enters dots instead of commas to specify a decimal place
string Ammount_Now = textbox1.Text.Replace('.', ',');//value text entered is 123.34
//The value of Ammount_Now is now 123,34
decimal value = 0;
bool Ammount_Good = decimal.TryParse(Ammount_Now, out value);
if(Ammount_Good)
{
//continue with method
// windows 8 returns true in the decimal.TryParse()
// windows 7 returns false in the decimal.TryParse()
// They both use .net framework 4.5
}
else
{
//failed parsing
}
}
OS 版本没有问题,您在不同语言环境的机器上测试了代码。
只要您在解析时使用正确的 CultureInfo,也无需将小数点替换为 "fix"。如果输入文本总是希望使用 .
作为小数点,你应该使用 Decimal.TryParse Method (String, NumberStyles, IFormatProvider, Decimal) 重载:
decimal.TryParse(Amount_Now,NumberStyles.Number,CultureInfo.InvariantCulture,out value)