问题描述
我有这个 bson 文档,我从 mongodb 中读取,使用 c# mongodb 驱动程序 v2.4.4.我只需要在 c# 代码中将其中的某些字段转换为十进制.我知道那里有一个双精度值,因此我尝试使用以下方法转换为十进制值:
I have this bson document which I read from mongodb, using c# mongodb driver v2.4.4. I just need to convert some field in it to decimal in a c# code. I know there is a double value there, therefore I try to convert to a decimal value using:
monto = Convert.ToDecimal(document["monto"].AsDouble)
但是,由于值是 39330000,我想驱动程序假定它是 Int32 并抛出此异常:
But, as the value is 39330000, I suppose the driver assumes it is a Int32 and throws this exception:
无法将MongoDB.Bson.BsonInt32"类型的对象转换为类型'MongoDB.Bson.BsonDouble'.
也许是因为它里面没有点 (.).
Maybe because it doesn't come with the dot (.) in it.
所以,我用它来转换为十进制:
So, I'm using this to convert to decimal:
monto = Convert.ToDecimal(document["monto"].ToString())
它之所以有效是因为 c# 可以将任何包含数字的字符串转换为十进制.
And it works because c# can convert to decimal any string that contains a number.
我的问题是:有没有更好的方法将 bson double 转换为 c#decimal,而不先将其转换为字符串?
My question is: is there a better way to convert a bson double to c# decimal, without converting it to a string first ?
谢谢,再见……
推荐答案
最好的选择可能是:
monto = document["monto"].ToDecimal();
之所以如此有效,是因为抽象的 BsonValue
类型实现了如下所示的方法:
The reason why this works so nicely is that the abstract BsonValue
type implements a method that looks like this:
public virtual decimal ToDecimal()
BsonValue
的具体实现(例如 BsonInt32
、BsonInt64
、BsonDouble
等)用无论驱动程序是否从存储的文档中反序列化 int、long 或 double,以下方法都能准确地为您提供所需的内容:
The concrete implementations of BsonValue
(e.g. BsonInt32
, BsonInt64
, BsonDouble
etc.) override this member with the below method which gives you precisely what you want, no matter if the driver deserializes an int, a long or a double from a stored document:
public override decimal ToDecimal()
{
return (decimal)_value;
}
或者,在您的特定情况下(如果范围内的所有文档都在其monto"字段中存储了一个 int),您可以简单地编写:
Alternatively, in your specific case (and if all documents in scope have an int stored in their "monto" field) you can simply write:
monto = Convert.ToDecimal(document["monto"].AsInt32)
甚至只是
monto = (decimal)(document["monto"].AsInt32)
语义相同.
这篇关于c# mongodb 驱动程序如何将 mongo double 值转换为 c# 十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!