【问题标题】:Convert.ChangeType problems with passing a doubleConvert.ChangeType 传递双精度的问题
【发布时间】:2014-07-16 09:11:47
【问题描述】:

我正在使用这行代码将字符串转换为int16int32double等类型:

var convertedValue = value == null ? null : Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);

谁能向我解释为什么convertedValue 设置为例如205.0value = "20,5"targetType 是双倍的?

感谢您的帮助。

【问题讨论】:

  • 这是什么意思,,不是InvariantCulture中的小数分隔符
  • 是的,我也想通了。调试时,我输入了我的 GUI 20.5,但在其他地方检索值时,ToString() 方法将此值更改为“20,5”。奇怪
  • 为什么奇怪? ToString() 将尊重当前的文化。当您执行Convert.ChangeType 时,您明确地覆盖了它。 doubles 没有什么文化可以随身携带。
  • 使用 CurrentCulture,但不是不变量,因为十进制的 afaik ToString(当然也是双精度)使用 CurrentCulture
  • 您希望发生什么?

标签: c# type-conversion


【解决方案1】:

它是一个小数分隔符。像 20000 可以用字符串写成 20,000。同样,当您将 20,000 转换为双倍时,它会给您 20000。

【讨论】:

    【解决方案2】:

    我在我的 VB.Net 项目中遇到了类似的问题。原因是编译器将带有逗号 ("20,5") 的值视为字符串,因为十进制值没有小数点,因此它将 "20,5" 转换为 205 。我通过使用点替换逗号解决了这个问题

    .ToString().Replace(",", ".")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多