amazon-web-servicesamazon-dynamodbboto3

Amazon DynamoDB changes number format with Boto3


I have this data to entry into AWS DynamoDB:

item = {
    "PK": {
        "S": "DEBUG"
    },
    "SK": {
        "S": "#ID_LOG#2025-10-09T07:48:31.105674+00:00"
    },
    "data": {
        "M": {
            "t": {
                "N": "1.00000000000000007629769841092E+50"
            }
        }
    }
}

I use this code to put it into the table:

db_client = boto3.client('dynamodb')
response = db_client.put_item(
    TableName = "mytable",
    Item = item
)

But the data inserted in the table is:

{
    "PK": {
        "S": "DEBUG"
    },
    "SK": {
        "S": "#ID_LOG#2025-10-09T07:48:31.105674+00:00"
    },
    "data": {
        "M": {
            "t": {
                "N": "100000000000000007629769841092000000000000000000000"
            }
        }
    }
}

Why? I need the original form to avoid errors.


Solution

  • You can suppress the rounding error like this:

    import boto3
    import json
    from boto3.dynamodb.conditions import Key
    from boto3.dynamodb.types import DYNAMODB_CONTEXT
    from decimal import Rounded
    
    DYNAMODB_CONTEXT.traps[Rounded] = 0
    
    db_client = boto3.client('dynamodb')
    db_table = boto3.resource('dynamodb').Table('Test')
    
    item = {
        "PK": {
            "S": "DEBUG"
        },
        "SK": {
            "S": "#ID_LOG#2025-10-09T07:48:31.105674+00:00"
        },
        "data": {
            "M": {
                "t": {
                    "N": "1.00000000000000007629769841092E+50"
                }
            }
        }
    }
    
    response = db_client.put_item(
        TableName = "Test",
        Item = item
    )
    
    query_args = { "KeyConditionExpression": Key('PK').eq("DEBUG") & Key('SK').eq("#ID_LOG#2025-10-09T07:48:31.105674+00:00") }
    response = db_table.query(**query_args)
    print(json.dumps(response["Items"], indent=4, default=str))
    

    For most applications dealing with very large scientific notation numbers like 10^50, the precision loss in the far decimal places is acceptable. But if you need exact precision for financial calculations or scientific data, you should reconsider your data storage approach, such as storing your number as a string.