【问题标题】:Set up dot instead of comma in numeric values在数值中设置点而不是逗号
【发布时间】:2012-02-27 22:11:49
【问题描述】:

我有新的 XmlDocument 对象,例如xml 是在我的程序中创建的...

我希望创建的 xml 中的所有数值默认使用点符号而不是逗号。

我可以做一些事情来声明一次,而不是解析每个十进制值吗?

即要在开头的某个地方设置这个点而不是逗号,直到最后都不要担心这个?

【问题讨论】:

  • 如果您想要 XML 中的小数点,但想在向用户显示值时使用小数点逗号,则必须当场指定。没有“仅在 xml 中使用点”设置。

标签: c# xml tostring numeric culture


【解决方案1】:

试试这个:

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

【讨论】:

  • 为什么不直接在 CurrentCulture 中分配 NumberDecimalSeperator?
  • @Brent Visual Studio 显示一个错误,提示“非静态字段、方法或属性 'CultureInfo.NumberFormat' 需要对象引用。”。因此,需要创建一个实例来访问相关属性。
【解决方案2】:

您可以使用value.ToString(CultureInfo.InvariantCulture) 将您的数值转换为字符串。或者您可以将当前区域性全局更改为使用点作为小数分隔符的区域性:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

【讨论】:

  • value.ToString(CultureInfo.InvariantCulture) 目前不工作:msdn.microsoft.com/en-us/library/29dxe1x2(v=vs.100).aspx
  • @Jonas,你指向的链接是关于String.ToString(IFormatProvider)。关于如何“保留”该参数的部分不适用于其他类型,仅适用于 String
  • 在我的版本 (.NET 4.5) 中是CultureInfo.GetCultureInfo("en-US")。完美运行。
  • 是的,效果很好,只是我还需要 GetCultureInfo
  • 对于预期目的而言,这是一个比公认答案更好的解决方案!
【解决方案3】:

Decimal.ToString(..)System.Globalization.CultureInfo.InvariantCulture 一起使用,就像应用了参数一样。

或者如果你想在全球范围内进行,请使用

CurrentCulture 使用Applicaton.CurrentCulture 属性设置为始终Invariant 1。

【讨论】:

  • 设置 Application.CurrentCulture 对我不起作用。
猜你喜欢
  • 2020-05-31
  • 2015-07-20
  • 1970-01-01
  • 2018-08-16
  • 2021-06-28
  • 2012-06-09
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多