Validate PostgreSQL monetary values: rounding, constraints and exact totals

Validate PostgreSQL monetary values: rounding, constraints and exact totals

Validate PostgreSQL monetary values: rounding, constraints and exact totals

An API request involving a monetary amount can succeed while the bill is off by the smallest monetary unit. Application logs alone are not enough to investigate. One common cause is that the database rounds the input before enforcing constraints. Another is that the application converts a decimal string to floating point before binding the parameter. Either path can let a successful write conceal a changed input value.

This lab uses temporary PostgreSQL objects in a separate test database on a dedicated server to build an acceptance test: first reproduce implicit rounding, then reject out-of-contract inputs, and finally check aggregates and application readback. It requires no changes to production tables and does not depend on specific hardware performance.

1. Define the monetary input contract

This example accepts only nonnegative decimal amounts with at most two decimal places and a maximum value of 9999999999.99. Negative numbers, values with a third decimal place, nulls, and non-finite values must all be rejected. These are the business rules for this lab, not universal rules for every accounting system. Refunds and reversals need their own definitions for signs and relationships between transactions.

The meaning of trailing zeros must also be explicit. This example treats 1.230 as having three decimal places and rejects it rather than automatically normalizing it to 1.23. If the product allows trailing zeros, normalize them first at a controlled entry point and retain the original request for traceability.

Amount validation and display formatting are not the same thing. Showing two decimal places in the interface does not prove that the database rejected extra decimal places. Rounding at query time does not prove that no information was lost during the write.

Use an administrative terminal with the PostgreSQL client installed, and connect to the test database through your existing authentication method. Do not put passwords on the command line. Run all subsequent SQL in the same session and roll back the entire experiment at the end.

2. Reproduce implicit rounding in a fixed-scale column

Start a transaction, then compare the input with the result of a fixed-scale conversion:

BEGIN;

SELECT
    '1.005'::numeric AS original_value,
    '1.005'::numeric(12,2) AS stored_value,
    '-1.005'::numeric(12,2) AS negative_value;

The expected results, in order, are 1.005, 1.01, and -1.01. The numeric type rounds ties away from zero. Do not assume it uses the default rounding mode of another language or library.

numeric(12,2) specifies total precision and decimal scale; it does not mean “raise an error if there are more than two decimal places.” When a value enters the target column, PostgreSQL first rounds it to the specified scale, then checks whether the integer part fits. As a result, the following constraint cannot catch the third decimal place in the original input:

CREATE TEMP TABLE rounded_amount (
    amount numeric(12,2) CHECK (scale(amount) <= 2)
);

INSERT INTO rounded_amount VALUES ('1.005');
SELECT amount, scale(amount) FROM rounded_amount;

The value is already 1.01: the constraint sees the converted value. If an application parameter, function parameter, or explicit cast uses numeric(12,2) earlier in the path, a strict constraint applied afterward cannot recover the discarded digits either.

3. Reject invalid values with unconstrained numeric

A strict entry point should first receive the decimal value without fixed-scale rounding, then check its range and scale. Define the temporary table as follows:

CREATE TEMP TABLE accepted_amount (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    amount numeric NOT NULL,
    CONSTRAINT amount_contract CHECK (
        amount NOT IN (
            'NaN'::numeric,
            'Infinity'::numeric,
            '-Infinity'::numeric
        )
        AND amount >= 0
        AND amount <= 9999999999.99
        AND scale(amount) <= 2
    )
);

INSERT INTO accepted_amount(amount)
VALUES ('0'), ('0.10'), ('0.20'), ('9999999999.99');

Do not omit NOT NULL: a SQL CHECK does not treat an expression that evaluates to unknown as a failure, so range conditions alone do not prohibit nulls. Non-finite values should also be explicitly rejected rather than left to the display layer’s rendering behavior.

Turn expected rejections into assertions

The following code tries each invalid input in turn. Expected constraint errors are caught; if a value unexpectedly passes, the code raises an exception to fail the acceptance test.

DO $body$
DECLARE
    candidate text;
BEGIN
    FOREACH candidate IN ARRAY ARRAY[
        '-0.01', '1.005', '1.230',
        '10000000000', 'NaN', 'Infinity', '-Infinity'
    ]
    LOOP
        BEGIN
            INSERT INTO accepted_amount(amount)
            VALUES (candidate::numeric);
            RAISE EXCEPTION 'Invalid amount accepted: %', candidate;
        EXCEPTION
            WHEN check_violation THEN
                NULL;
        END;
    END LOOP;

    BEGIN
        INSERT INTO accepted_amount(amount) VALUES (NULL);
        RAISE EXCEPTION 'Null amount accepted';
    EXCEPTION
        WHEN not_null_violation THEN
            NULL;
    END;
END
$body$;

Empty strings and nonnumeric text fail during type conversion, which is a different error from a constraint rejection. The API should log conversion failures separately from business-rule failures, but neither should fall back to zero and continue posting the entry.

4. Check aggregates and the application parameter-binding path

An exact column type cannot undo a floating-point conversion inside a query. Clear the lab data first, then validate against an explicit expected decimal value:

TRUNCATE accepted_amount;

INSERT INTO accepted_amount(amount)
VALUES ('0.10'), ('0.20'), ('12.34');

SELECT
    sum(amount) AS total,
    pg_typeof(sum(amount)) AS total_type,
    sum(amount) = 12.64::numeric AS exact_match
FROM accepted_amount;

The expected total is 12.64, the type should be numeric, and the comparison should return true. Do not cast to double precision before aggregation, and do not use a formatted string as input to the next calculation.

In the application, use a decimal type supported by the driver, or bind the original decimal string as a parameter and then cast it to unconstrained numeric. Never construct SQL by concatenating strings. Test requests should cover at least 0.10, 1.005, the maximum value, and a value above the maximum. Inspect the values actually stored in the database, not just the response status.

When there are no rows, sum returns null. Use coalesce only if the business rules explicitly define “no line items” as zero. Also check whether the JSON encoder or reporting tool converts values to floating point after readback, so that values correct inside the database do not lose precision on the way out.

5. Pre-release checks and cleanup

Before moving an existing fixed-scale column to a strict input path, review every write path. Historical values with only two decimal places do not prove that historical requests also had only two. Rounding that has already occurred cannot be reconstructed from the current tables alone. Check stored procedure parameters, import scripts, and application models individually.

The acceptance record should include at least the following checks:

  • Valid boundary values are stored successfully, invalid boundary values actually raise errors, and failed operations leave no business line items behind.
  • When a transaction contains both valid and invalid line items, the caller rolls back the entire transaction rather than mistaking partial success for a complete commit.
  • Database calculations, driver readback, and API serialization introduce no binary floating-point conversions.
  • Rounding rules have explicit business approval. When rounding is needed, it happens only at the agreed stage, not silently through a column conversion.

When the lab is complete, run:

ROLLBACK;

The rollback undoes the temporary tables created in this session and the lab’s writes. Final acceptance should rest on three sets of evidence: valid values remain unchanged, invalid values are rejected, and totals are consistent. A monetary-sounding column name or a page that happens to display two decimal places is not enough.

Frequently asked questions

Does numeric(12,2) reject values with three decimal places?

Not just because a third decimal place exists. PostgreSQL rounds to the target scale before checking the integer range. To reject excess decimal places, use unconstrained numeric with explicit scale and range checks.

Can converting a floating-point value to numeric recover the original amount?

Not reliably. Once the original decimal input has been converted to binary floating point, a later conversion cannot reliably reconstruct it. Bind a decimal type or the original decimal string and validate it at the database boundary.

EPYC 7543P Dedicated Server

From $444/month; total due = monthly rate × number of months. No discounts, setup fees, or contracts.

Choose a dedicated server configuration based on workload and budget

Check memory options, disk layout, and sustained bandwidth, then select the operating system and billing term. Plan images and off-site backups separately.