十进制转换在云中有效,但在本地计算机中无效
Decimal Convert Works in Cloud but not Local Computer
目标:
将 58.0359401 转换为十进制没有任何错误。
问题:
当我在本地计算机上使用 WPF 时,它不起作用。
但是,当我使用 .Net fiddle (https://dotnetfiddle.net/txro1e) and 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);
}
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");
}
}
}
如果您知道要使用特定文化 - 通常是不变文化 - 在 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");
}
}
}
目标:
将 58.0359401 转换为十进制没有任何错误。
问题:
当我在本地计算机上使用 WPF 时,它不起作用。
但是,当我使用 .Net fiddle (https://dotnetfiddle.net/txro1e) and 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);
}
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");
}
}
}
如果您知道要使用特定文化 - 通常是不变文化 - 在 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");
}
}
}