Are Python financial calculations off by 1 yen? Checking Decimal and rounding order

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article was created using an automated generation workflow powered by generative AI. We referenced the specifications of Python's standard library Decimal and organized a procedure to verify fractional rounding of billing amounts using dummy data.

Verification Status: 🧪 Sample code verified locally and not yet verified in a production environment.
We check calculation results using fictitious monetary amounts. Actual billing systems, tax fractional rounding rules, and reconciliations with Excel have not been verified.

Are Python financial calculations off by 1 yen? Checking Decimal and rounding order

The invoice total differs by 1 yen depending on the system. In such cases, checking merely whether decimal places were rounded to the nearest integer may not reveal the cause.Which numeric type was used, at what point the rounding was performed, and which rounding rule was adoptedbecause these factors change the result.

Python'sfloatis a binary floating-point number and cannot always accurately represent decimal numbers such as 0.1. On the other hand, the standard librarydecimal.Decimalcan be used for decimal calculations, andquantize()allows you to specify the number of decimal places and the rounding mode. However,Decimalsimply using it does not guarantee that billing processing will be correct.You must first determine the business rules for fractional rounding.

Target environment and safe experimentation methods

ItemContent
TargetPython 3, standard librarydecimal
Required permissionsCan be executed by a standard user. Administrator privileges are not required.
InputFictional unit prices, quantities, and tax rates only
External impactNo network connection, actual file modification, or external service calls
What to verifyCreate Decimals from strings and compare line-item rounding with total-level rounding

Assume a tax rate of 10% as an example. This isa fictional condition for explaining the calculation methodand does not determine the legality of actual tax classifications, applicable tax rates, or invoice system rounding rules.

Explicitly specify the rounding method using Decimal

Save the following code asdecimal_demo.pyand run it withpython decimal_demo.py.Decimal('0.10')By passing it as a string like this, you avoid introducing the approximation errors inherent in binary floating-point numbers.

from decimal import Decimal, ROUND_HALF_UP

# 架空の明細。実際の顧客情報や請求データは使わない。

prices = [Decimal('15'), Decimal('15'), Decimal('15')]
rate = Decimal('0.10')
yen = Decimal('1')

# 例示用の規則: 0.5以上を切り上げて整数円に丸める。

def round_yen(value):
    return value.quantize(yen, rounding=ROUND_HALF_UP)

# 明細ごとに税額を丸める方法。

per_line = [round_yen(price * rate) for price in prices]
line_total = sum(per_line, Decimal('0'))

# 税額を先に合算してから一度だけ丸める方法。

subtotal = sum(prices, Decimal('0'))
invoice_total = round_yen(subtotal * rate)

print('明細ごとの税額:', [str(x) for x in per_line])
print('明細単位の税額合計:', line_total)
print('合計単位の税額:', invoice_total)
print('差額:', line_total - invoice_total)

The expected output is as follows.

明細ごとの税額: ['2', '2', '2']
明細単位の税額合計: 6
合計単位の税額: 5
差額: 1

10% of 15 yen is 1.5 yen. If three line items are each rounded up to 2 yen, the total becomes 6 yen. In contrast, 10% of the total of 45 yen for three items is 4.5 yen, which rounds to 5 yen when rounded only once.Even if both calculation formulas can be executed as code, they must not be mixed on the same invoice. The unit of calculation and the rounding method to be adopted are determined by business rules.

Changing only one condition to verify the cause

The abovepricesis changed from three items of 15 yen to the following three items of 10 yen.

prices = [Decimal('10'), Decimal('10'), Decimal('10')]

This time, the tax amount per line item is 1 yen, and 10% of the total amount of 30 yen is 3 yen, so both result in 3 yen. From this comparison, it can be seen that how fractions appear depends on the line item amounts. It is not a phenomenon where "there is always a 1-yen discrepancy."

Caution when passing float to Decimal

Decimal(0.1)andDecimal('0.1')do not have the same meaning. Because the former converts a value already approximated as a binary floating-point number into Decimal, it may retain a value different from the intended decimal 0.1. When handling amounts from external CSVs or JSON, also verify whether the string representation of the amount can be preserved and whether it has not become a float at the time of input.

Note that Python's built-inround()andROUND_HALF_UPalso do not follow the same rules. Built-in rounding has behavior that rounds ties toward the even number, and it does not implicitly substitute for business rules for monetary amounts.

Troubleshooting when a discrepancy occurs

Observed phenomenonWhat to check firstDirection of resolution
Line item total and invoice total differ by 1 yenLine item level or invoice levelCompare calculation units with the specification document
0.1 and similar values become long decimalsDecimal(float値)whether it is notCheck string input and conversion path
Rounding of 0.5 differs from expectationround()orquantize()orUse an explicit rounding method
Differences may or may not occur depending on the dataDoes the unit price or quantity result in fractional values?Reproduce using hypothetical boundary values
Results do not match the accounting softwareTax rate, discount order, rounding unitConfirm business specifications and applicable systems with the person in charge

Keep an audit trail of calculations when used for business purposes

In billing processing, not only the amount,original unit price, quantity, tax rate, rounding unit, rounding method, and the version of the applied calculation rulemaking them traceable makes it easier to explain discrepancies. There is no need to output actual data entirely to logs. Avoid confidential client names and line-item details, and record anonymized data for validation along with the calculation conditions.

Practical tax calculation involves laws, regulations, and reporting requirements. Rather than copying this sample'sROUND_HALF_UPdirectly into production billing logic, it is important to align with rules approved by the organization's accounting and tax personnel and separately prepare tests for boundary values, discounts, returns, negative numbers, mixed tax rates, and aggregation units.

Official Information / Primary Sources

Verification Scope

The provided code was executed locally and verified against the expected outputs. Integration with actual billing and accounting software, legal compliance, and rendering in Windows or Excel have not been verified. Fictional data was used for testing, and the accuracy of real-world transactions is not guaranteed.

Document information

Article title
Are Python financial calculations off by 1 yen? Checking Decimal and rounding order
Published
Updated
Source
https://papanda925.com/?p=18662&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL