Fundamentals 7 min read

How to Convert decimal.Decimal to float in Various Python Data Structures

This tutorial demonstrates multiple ways to transform Python decimal.Decimal objects into native float values across different data structures such as single variables, lists, dictionaries, nested collections, pandas DataFrames, JSON strings, tuples, and sets, while highlighting precision considerations.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
How to Convert decimal.Decimal to float in Various Python Data Structures

Example 1: Convert a single Decimal object

from decimal import Decimal
# 创建一个 Decimal 对象
decimal_value = Decimal('123.456')
# 转换为 float
float_value = float(decimal_value)
print(float_value)  # 输出: 123.456

Example 2: Convert Decimal objects in a list

from decimal import Decimal
# 创建一个包含 Decimal 对象的列表
decimal_list = [Decimal('1.1'), Decimal('2.2'), Decimal('3.3')]
# 转换为 float 列表
float_list = [float(d) for d in decimal_list]
print(float_list)  # 输出: [1.1, 2.2, 3.3]

Example 3: Convert Decimal objects in a dictionary

from decimal import Decimal
# 创建一个包含 Decimal 对象的字典
decimal_dict = {'a': Decimal('1.1'), 'b': Decimal('2.2'), 'c': Decimal('3.3')}
# 转换为 float 字典
float_dict = {k: float(v) for k, v in decimal_dict.items()}
print(float_dict)  # 输出: {'a': 1.1, 'b': 2.2, 'c': 3.3}

Example 4: Convert Decimal objects in a nested structure

from decimal import Decimal
# 创建一个包含 Decimal 对象的嵌套结构
nested_structure = {
    'key1': [Decimal('1.1'), Decimal('2.2')],
    'key2': {'subkey1': Decimal('3.3'), 'subkey2': Decimal('4.4')}
}

def convert_decimal_to_float(obj):
    if isinstance(obj, Decimal):
        return float(obj)
    elif isinstance(obj, dict):
        return {k: convert_decimal_to_float(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_decimal_to_float(item) for item in obj]
    else:
        return obj

float_structure = convert_decimal_to_float(nested_structure)
print(float_structure)  # 输出: {'key1': [1.1, 2.2], 'key2': {'subkey1': 3.3, 'subkey2': 4.4}}

Example 5: Convert Decimal objects in a pandas DataFrame

import pandas as pd
from decimal import Decimal
# 创建一个包含 Decimal 对象的 DataFrame
data = {
    'A': [Decimal('1.1'), Decimal('2.2')],
    'B': [Decimal('3.3'), Decimal('4.4')]
}
df = pd.DataFrame(data)
# 转换为 float DataFrame
float_df = df.applymap(lambda x: float(x) if isinstance(x, Decimal) else x)
print(float_df)  # 输出:
#          A    B
# 0  1.10000  3.3
# 1  2.20000  4.4

Example 6: Convert Decimal objects in a JSON string

import json
from decimal import Decimal
# 创建一个包含 Decimal 对象的 JSON 字符串
json_str = '{"a": 1.1, "b": 2.2}'
# 自定义 JSON 解析函数以处理 Decimal

def parse_decimal(dct):
    for key, value in dct.items():
        if isinstance(value, str) and '.' in value:
            try:
                dct[key] = float(Decimal(value))
            except Exception:
                pass
    return dct

parsed_dict = json.loads(json_str, object_hook=parse_decimal)
print(parsed_dict)  # 输出: {'a': 1.1, 'b': 2.2}

Example 7: Convert Decimal objects in a tuple

from decimal import Decimal
# 创建一个包含 Decimal 对象的元组
decimal_tuple = (Decimal('1.1'), Decimal('2.2'))
# 转换为 float 元组
float_tuple = tuple(float(d) for d in decimal_tuple)
print(float_tuple)  # 输出: (1.1, 2.2)

Example 8: Convert Decimal objects in a set

from decimal import Decimal
# 创建一个包含 Decimal 对象的集合
decimal_set = {Decimal('1.1'), Decimal('2.2'), Decimal('3.3')}
# 转换为 float 集合
float_set = {float(d) for d in decimal_set}
print(float_set)  # 输出: {1.1, 2.2, 3.3}

Example 9: Convert Decimal objects in a dictionary while preserving original types

from decimal import Decimal
# 创建一个包含 Decimal 对象的字典
decimal_dict = {'a': Decimal('1.1'), 'b': Decimal('2.2'), 'c': Decimal('3.3')}
# 转换为 float 字典(保持原始数据类型)

def convert_dict_decimal_to_float(d):
    return {k: float(v) if isinstance(v, Decimal) else v for k, v in d.items()}

float_dict = convert_dict_decimal_to_float(decimal_dict)
print(float_dict)  # 输出: {'a': 1.1, 'b': 2.2, 'c': 3.3}

Example 10: Convert Decimal objects in a list while preserving original types

from decimal import Decimal
# 创建一个包含 Decimal 对象的列表
decimal_list = [Decimal('1.1'), Decimal('2.2'), Decimal('3.3')]
# 转换为 float 列表(保持原始数据类型)

def convert_list_decimal_to_float(lst):
    return [float(item) if isinstance(item, Decimal) else item for item in lst]

float_list = convert_list_decimal_to_float(decimal_list)
print(float_list)  # 输出: [1.1, 2.2, 3.3]

Summary

The above examples show how to convert data of type decimal.Decimal to Python's float type and apply the conversion to various data structures; however, converting to float may lose precision, so avoid it in high‑precision calculations.

PythonJSONTutorialpandasdata-structuresDecimalfloat-conversion
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.