vb.net 语言不变 Double.ToString()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19295560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:26:49  来源:igfitidea点击:

Language invariant Double.ToString()

c#.netvb.net

提问by f1wade

I am passing a double across a network, currently I do

我正在通过网络传递一个双倍,目前我这样做

double value = 0.25;
string networkMsg = "command " + value;

the networkMsgis fine in english where its 0.25 and french where its 0,25, but when i go from a french computer to an english computer one side is making it 0.25 and the other is trying to read 0,25.

networkMsg是英文得很好,它的0.25和法国在那里的0.25,但是当我从法国计算机去参加英语计算机一面使它0.25,另一种是试图读取0.25。

So i can to use region invariant methods in my code.

所以我可以在我的代码中使用区域不变方法。

I have found Val(networkMsg) that will always read 0.25 no matter the region.

我发现networkMsg无论在哪个地区,Val( ) 的读数总是 0.25。

but I cannot find a guaranteed way of converting from value to 0.25 region invariant. would value.toString("0.0")work?

但我找不到从值转换为 0.25 区域不变量的有保证的方法。会value.toString("0.0")工作吗?

回答by Marc Gravell

The .in the format specifier "0.0"doesn't actually mean "dot" - it means "decimal separator" - which is ,in France and several other European cultures. You probably want:

.格式说明"0.0",实际上并不意味着“点” -它的意思是“小数点分隔符” -这是,在法国和其他一些欧洲文化。你可能想要:

value.ToString(CultureInfo.InvariantCulture)

or

或者

value.ToString("0.0", CultureInfo.InvariantCulture)

For info, you can see this (and many other things) by inspecting the frculture:

有关信息,您可以通过检查fr文化来看到这一点(以及许多其他内容):

var decimalSeparator = CultureInfo.GetCultureInfo("fr")
            .NumberFormat.NumberDecimalSeparator;

回答by Jeppe Stig Nielsen

Use:

用:

string networkMsg = "command " + value.ToString(CultureInfo.InvariantCulture);

or:

或者:

string networkMsg = string.Format(CultureInfo.InvariantCulture, "command {0}", value);

This needs using System.Globalization;in the top of your file.

这需要using System.Globalization;在您的文件的顶部。

Note: If you need full precision, so that you can restore the exact double again, use the Formatsolution with the roundtrip format{0:R}, instead of just {0}. You can use other format strings, for example {0:N4}will insert thousands separators and round to four dicimals (four digits after the decimal point).

注意:如果您需要全精度,以便您可以再次恢复精确的双精度值,请使用Format具有往返格式的解决方案{0:R},而不仅仅是{0}. 您可以使用其他格式字符串,例如{0:N4}将插入千位分隔符并四舍五入为四个小数(小数点后四位)。



Since C# 6.0 (2015), you can now use:

从 C# 6.0 (2015) 开始,您现在可以使用:

string networkMsg = FormattableString.Invariant($"command {value}");

回答by Jon

Specify the invariant culture as the format provider:

将固定区域性指定为格式提供程序:

value.ToString(CultureInfo.InvariantCulture);