转换数字而不带前导零以在 C# 中使用

Convert Number without leading zero for using in C#

我有一个 Oracle 视图,它为我提供了这些数据:

DATUM              STUNDE LAUFZEIT
-------------- ---------- -----------
30.10.14 00:00         11  ,433333333

LAUFZEIT 声明为 NUMBER。我需要将列转换为 0,433333333 或四舍五入为 0,4 的哪种格式?

我已经尝试过一些像 Convert.ToSingle(reader.GetValue(2)) 这样的类型,但总是得到像

这样的错误

System.OverflowException: Arithmetic operation resulted in an overflow

谢谢!

您始终可以在解析前自行添加前导零。在数字的开头添加零永远不会改变它。

Convert.ToSingle('0' + reader.GetString(2).Replace(',','.'))应该做。

我建议在解析之前使用 reader.GetString()。

另外最好做:

Single a ;
if(Single.TryParse('0' + reader.GetString(2).Replace(',','.')), out a))
{
    //Success code here
}
else
{
    //Code to execute if string was not parsable here
}

这样你就不会得到异常

你必须提到一个当前的文化:

  Object source = ",433333333";

  // This will fail with exception - Neutral Culture uses decimal point, not comma
  //Single single = Convert.ToSingle(source, CultureInfo.InvariantCulture);

  // OK: Russian culture (ru-RU) uses decimal comma, not decimal point
  Single single = Convert.ToSingle(source, new CultureInfo("ru-RU"));

要以所需形式表示值,请使用格式化,例如对于 0,4:

  // F1 - one floating point
  // "ru-RU" for decimal comma
  String result = single.ToString("F1", new CultureInfo("ru-RU"));

编辑:已在 异常堆栈跟踪 上看到,即

Arithmetic operation resulted in an overflow. at Oracle.DataAccess.Types.DecimalConv.GetDecimal(IntPtr numCtx)

可以断定问题出在

`Oracle.DataAccess.Types.DecimalConv.GetDecimal`

错误的根源可能在于 Oracle Number(36) 或类似的东西比 .Net Decimal 更大。由于您无法更改 Oracle.DataAccess 库,因此您可以仅在查询中转换为字符串:

  select ...
         cast(LAUFZEIT as VarChar2(40)), 
         ...