gpt4 book ai didi

c# - 当值为 "0.00000"时,Convert.ToInt64 失败

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:01 25 4
gpt4 key购买 nike

5 我的代码是这样的

protected long Getvalue()
{
DataTable dt = GetDataBaseValue();
if (dt.Rows.Count > 0)
{
return Convert.ToInt64(dt.Rows[0]["BALANCE"].ToString());
}
return 0;
}

dt.Rows[0]["BALANCE"].ToString()=0.00000 我在这里遇到错误

PS: 我试着这样做 return long.Parse(...) 但我得到了同样的错误

最佳答案

问题是“0.00000”是一个字符串,它是"parsing to a long"无效格式 1.

但是,省略 ToString() 转换可能就足够了,因此会出现上述错误,具体取决于数据库实际返回的类型。如果数据库返回适当的 double / float /小数,那么即使失去精度,以下“将起作用”也是如此。

// Source is a double
Convert.ToInt64(0.0d) // -> 0
Convert.ToInt64(0.5d) // -> 0 (half-even rounding)
Convert.ToInt64(1.5d) // -> 2 (half-even rounding)
Convert.ToInt64(double.MaxValue) // -> OverflowException

// Source is a string
Convert.ToInt64("0") // -> 0
Convert.ToInt64("0.0") // -> FormatException: "not in a correct format"

如果由于某些不可纠正的原因,数据库返回给定格式的字符串,首先将字符串转换为 double /十进制(支持这种格式)就足够了,然后到很长。类似的溢出和精度损失情况是可能的。

long v = (long)Convert.ToDecimal(dt.Rows[0]["BALANCE"]);

默认情况下,.NET 将解析符合模式 \s*[-+]?\d+\s* 的字符串中的整数值(例如 int、long) 否则将抛出 FormatException;这在链接文档中有更详细的讨论。

关于c# - 当值为 "0.00000"时,Convert.ToInt64 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398984/

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