C#: Double 47.11 -> 47.109999999999999

I have a problem with values of type double. I’m trying to create a BsonValue with the value 47.11. I tried new BsonDouble() and BsonValue.Create(). In both options the driver (MongoDB.Driver 2.19.0) creates a BsonValue of type double, but with a wired value. Instead of 47.11 I get 47.109999999999999. The same happens, when I use document.ToJson() I also get the wrong value.
When I look at the document in Studio 3T the value is correct (47.11).

What am I doning wrong?
12-06-_2023_15-36-06x

Darius,

Welcome to the MongoDB forum. I understand that you’re having trouble with the precision of doubles in BSON. There’s a few ways to deal with this, but the simplest will be to store these values using the Decimal128 type. Here’s some useful articles for that:

  1. API docs
  2. Modeling Monetary Data
  3. History of Decimals in BSON
  4. Example with C# code

Thx for your help. I tried, but it’s the same problem:
12-06-_2023_17-35-43

Hi Darius-- this is more of a question about C# than MongoDB. You’ll need to let C# know that you want to use that decimal as a monetary value. You can do that by appending an ‘M’ to the value declaration, e.g.:

var bsonDecimal = new BsonDecimal128(47.11M)

Here’s the relevant C# documentation:

1 Like

This was a simplified example. Of course the value is not hard coded. But your hint helped me:
13-06-_2023_08-57-21

I have to cast a double variable into decimal, then it works.
Thx.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.