Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# mongodb driver how to cast a mongo double value to a c# decimal one

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)

But, as the value is 39330000, I suppose the driver assumes it is a Int32 and throws this exception:

Unable to cast object of type 'MongoDB.Bson.BsonInt32' to type '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())

And it works because c# can convert to decimal any string that contains a number.

My question is: is there a better way to convert a bson double to c# decimal, without converting it to a string first ?

Thanks and bye ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best option would probably to go with this:

monto = document["monto"].ToDecimal();

The reason why this works so nicely is that the abstract BsonValue type implements a method that looks like this:

public virtual decimal ToDecimal()

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;
}

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)

or even just

monto = (decimal)(document["monto"].AsInt32)

which are semantically identical.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...