Wha*_*sUP 1 c# wpf visual-studio-2017
目标:
将 58.0359401 转换为十进制,没有任何错误。
问题:
当我在本地计算机上使用 WPF 时,它不起作用。
但是,当我使用 .Net fiddle ( https://dotnetfiddle.net/txro1e ) 和 OnlineGDB ( https://onlinegdb.com/HkWbvR-AU ) 时,它可以工作。
问题是:
如果在本地计算机上使用源代码,是否得到相同的结果?
如果没有,你如何解决它以实现目标?
如果不是,怎么可能达到两种不同的结果?
谢谢!
private void Button1_Click(object sender, RoutedEventArgs e)
{
string test1 = "58.0359401";
decimal test2 = 58.0359401M;
decimal output;
bool isTrue = decimal.TryParse(test1, out output);
Console.WriteLine(isTrue);
}
Run Code Online (Sandbox Code Playgroud)
decimal.TryParse除非您指定,否则将使用当前的默认文化。这意味着如果您的默认文化使用除 '.' 以外的其他内容。作为小数点分隔符,但你有一个字符串,它不使用“” 作为小数点分隔符,您会遇到问题。例如:
using System;
using System.Globalization;
class Test
{
static void Main()
{
// Change this to "en" and it passes...
CultureInfo.CurrentCulture = new CultureInfo("fr");
string text = "1.5";
if (decimal.TryParse(text, out var result))
{
Console.WriteLine($"Parsed as: {result}");
}
else
{
Console.WriteLine("Parsing failed");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您知道要使用特定区域性 - 通常是不变区域性 - 在decimal.TryParse调用中指定:
using System;
using System.Globalization;
class Test
{
static void Main()
{
// Even if the current culture is French, the parse succeeds.
CultureInfo.CurrentCulture = new CultureInfo("fr");
string text = "1.5";
if (decimal.TryParse(text, NumberStyles.Number,
CultureInfo.InvariantCulture, out var result))
{
// Prints "Parsed as 1,5" because it uses the default culture
// for formatting
Console.WriteLine($"Parsed as: {result}");
}
else
{
Console.WriteLine("Parsing failed");
}
}
}
Run Code Online (Sandbox Code Playgroud)