gpt4 book ai didi

c# - 十进制转换在云端工作,但不适用于本地计算机

转载 作者:行者123 更新时间:2023-12-02 19:24:40 25 4
gpt4 key购买 nike

目标:
将 58.0359401 转换为十进制,没有任何错误。

问题:
当我在本地计算机上使用 WPF 时,它不起作用。
但是,当我使用 .Net fiddle ( https://dotnetfiddle.net/txro1e ) 和 OnlineGDB ( https://onlinegdb.com/HkWbvR-AU ) 时,它可以工作。

问题是:
如果您在本地计算机上使用源代码,会得到相同的结果吗?
如果不是,你如何解决它以达到目标?

如果不是,怎么可能得到两种不同的结果?

谢谢!

enter image description here

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");
}
}
}

关于c# - 十进制转换在云端工作,但不适用于本地计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62570524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com