Check Money Exactly With BigDecimal in REST Assured
Learn how REST Assured reads JSON numbers, why the default Float can't hold money, how to read decimals as BigDecimal with JsonConfig, why comparesEqualTo beats equalTo, and when closeTo is the right choice.
A bank statement has to add up: the opening balance plus every transaction is exactly the closing balance, not almost. Your statement test adds the six amounts, and the sum comes back as 1407.650001525879. Then a check of the opening balance fails, because 1000.00 isn’t 1000. In this guide, you’ll learn how REST Assured reads JSON numbers, read money as BigDecimal, and compare amounts exactly.
Level: Intermediate · Time: 20 minutes · Part of: Module 3: Validating Responses in Depth, section 3
What You’ll Build
You’ll build a test class called NumbersAndMoneyTest with seven tests. They read the same transactions with three number types, and prove which comparisons are exact, which are strict about scale, and which allow a tolerance.
All seven tests send this request and check this response:
1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001/transactions HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{"balance":{"opening":1000.00,"closing":2407.65},"transactions":[{"id":"tx-1","amount":2500.00, ...}, ...]}
When you’re done, Maven reports seven passing tests:
1
2
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- See the default number types.
- Read money as
BigDecimal. - Add up amounts exactly.
- Compare approximate values.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you’ve compared a decimal with the
fsuffix, as in Check Every Part of an HTTP Response, and you can filter a list withfindAll { .. }, from Filter JSON Lists With GPath in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
NumbersAndMoneyTestin a newsection_03package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
NumbersAndMoneyTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Filter JSON Lists With GPath in REST Assured.
Out of scope: this guide doesn’t cover setting the number type once for a whole suite, or extracting amounts into Java objects; they’re taught in Module 5 and Module 4.
Understand JSON Numbers in REST Assured
The problem. JSON has one number type, but Java has many. REST Assured has to pick one for each number in the body, and the default it picks for decimals can’t hold most amounts exactly. For one value you rarely notice. When a test adds amounts together, the small errors add up, and an exact statement check fails.
The concept. REST Assured picks a Java type for each number:
- A whole number becomes an
Integer, or aLongwhen it’s too big for anInteger. - A decimal becomes a
Floatby default, or aDoublewhen it’s too big for aFloat.
A Float holds about seven significant digits in binary, so -42.35 is stored as the nearest binary value, not as -42.35. JsonConfig changes the type used for decimals: NumberReturnType.BIG_DECIMAL reads them as BigDecimal, which stores decimal values exactly. A BigDecimal has a value and a scale, the number of digits after the point, so 1000.00 has scale 2 and 1000 scale 0.
When to use each. Pick the number type and the matcher from what the value means:
| Value | Number type | Matcher |
|---|---|---|
| A count, an id or a status | Default (Integer) | equalTo(6) |
| Money | BIG_DECIMAL | comparesEqualTo(new BigDecimal("2407.65")) |
| A measurement | DOUBLE | closeTo(-42.35, 0.001) |
| A quick check of a decimal | Default (Float) | equalTo(-42.35f) |
Read money as BigDecimal, and compare its value, not its scale.
Meet the API Under Test
The tests use the Transactions API and account acc-1001 from Filter JSON Lists With GPath in REST Assured. The parts that matter here are the balance and the amounts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{
"balance": { "opening": 1000.00, "closing": 2407.65 },
"transactions": [
{ "id": "tx-1", "type": "CREDIT", "amount": 2500.00, ... },
{ "id": "tx-2", "type": "DEBIT", "amount": -42.35, ... },
{ "id": "tx-3", "type": "DEBIT", "amount": -1100.00, ... },
{ "id": "tx-4", "type": "DEBIT", "amount": -60.00, ... },
{ "id": "tx-5", "type": "DEBIT", "amount": -40.00, ... },
{ "id": "tx-6", "type": "CREDIT", "amount": 150.00, ... }
]
}
The statement adds up:
| Movement | Sum |
|---|---|
| The four debits | -1242.35 |
| The two credits | 2650.00 |
| All six amounts | 1407.65 |
And 1000.00 + 1407.65 is the closing balance, 2407.65.
Your tests check these fields:
transactions[1].amount,-42.35, the first amount that isn’t a whole number.balance.openingandbalance.closing, which carry two decimals.- The sums of
transactions.amount, which only come out exact withBigDecimal.
See the Default Number Types
Set Up the Test Class
Goal: create the test class with a helper that sends the request, and one that reads decimals as BigDecimal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.javanibble.module_03.section_03;
import static io.restassured.RestAssured.given;
import static io.restassured.config.JsonConfig.jsonConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.comparesEqualTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;
import com.javanibble.transactions.TransactionsApi;
import io.restassured.common.config.NumberReturnType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import java.math.BigDecimal;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class NumbersAndMoneyTest {
private static TransactionsApi api;
@BeforeAll
static void startApi() {
api = TransactionsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification transactionsApi() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH);
}
private static ValidatableResponse transactions(RequestSpecification request) {
return request.when().get("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID).then();
}
private static RequestSpecification withBigDecimals() {
return transactionsApi().config(config().jsonConfig(jsonConfig().numberReturnType(NumberReturnType.BIG_DECIMAL)));
}
}
What’s happening:
transactions(request)sends the transactions request with whatever specification it’s given, so each test can choose the number type.withBigDecimals()setsJsonConfigon the request, so every decimal in its response is read as aBigDecimal.config(..)applies the setting to this request only, asHeaderConfigdid in Send Headers and Cookies in REST Assured.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Since REST Assured 6.3,
NumberReturnTypelives inio.restassured.common.config. The olderJsonPathConfig.NumberReturnTypeis deprecated, so import the new one.
Read a Whole Number
Goal: show that a whole number is an Integer.
1
2
3
4
@Test
void wholeNumbersAreIntegers() {
transactions(transactionsApi()).body("transactions.size()", equalTo(6));
}
What’s happening:
size()returns a whole number, which REST Assured gives you as anInteger.equalTo(6)compares with anInteger, so it matches. No number type needs to change for counts.
Checkpoint: run NumbersAndMoneyTest from your IDE. One test runs and passes.
Read a Decimal as a Float
Goal: show what the default Float matches and what it doesn’t.
1
2
3
4
5
6
7
@Test
void decimalsAreFloatsByDefault() {
transactions(transactionsApi())
.body("transactions[1].amount", instanceOf(Float.class))
.body("transactions[1].amount", equalTo(-42.35f))
.body("transactions[1].amount", not(equalTo(-42.35)));
}
What’s happening:
instanceOf(Float.class)proves the default type.equalTo(-42.35f)passes, because both sides are the sameFloat.equalTo(-42.35)fails, because-42.35is aDouble, andFloat.equals(..)is false for anyDouble. The test wraps it innot(..)to prove it.
Checkpoint: run the class again. Two tests pass.
A
Doublenever equals aFloat. Withoutnot(..), the check fails withExpected: <-42.35>andActual: <-42.35F>: the values look the same, and theFis the only clue.
Read Money as BigDecimal
Read Decimals as BigDecimal
Goal: read an amount and the closing balance as exact decimals.
1
2
3
4
5
6
7
@Test
void decimalsAsBigDecimal() {
transactions(withBigDecimals())
.body("transactions[1].amount", instanceOf(BigDecimal.class))
.body("transactions[1].amount", equalTo(new BigDecimal("-42.35")))
.body("balance.closing", equalTo(new BigDecimal("2407.65")));
}
What’s happening:
withBigDecimals()makestransactions[1].amountaBigDecimal.- The expected values are built from strings, so they’re exact too.
equalTo(..)passes here because both sides have the same value and the same scale, two decimals.
Checkpoint: run the class again. Three tests pass.
Always build the expected value from a string.
new BigDecimal(-42.35)takes adouble, which is already inexact: it’s-42.35000000000000142108547152020037174224853515625.
Compare the Value, Not the Scale
Goal: show why equalTo(..) fails on 1000.00 and comparesEqualTo(..) doesn’t.
1
2
3
4
5
6
@Test
void equalToIsStrictAboutScaleButComparesEqualToIsNot() {
transactions(withBigDecimals())
.body("balance.opening", not(equalTo(new BigDecimal("1000"))))
.body("balance.opening", comparesEqualTo(new BigDecimal("1000")));
}
What’s happening:
BigDecimal.equals(..)compares the value and the scale, so1000.00(scale 2) isn’t equal to1000(scale 0).- Without the
not(..), the check fails withExpected: <1000>andActual: <1000.00>. comparesEqualTo(..)usescompareTo(..), which compares only the value. For money, that’s almost always what you want, so use it by default.
Checkpoint: run the class again. Four tests pass.
Add Up Amounts Exactly
Sum a Filtered List
Goal: add up the debits and the credits.
GPath’s sum() adds a list of numbers. With BigDecimal values, the result is exact:
1
2
3
4
5
6
@Test
void sumsAreExactWithBigDecimal() {
transactions(withBigDecimals())
.body("transactions.findAll { it.type == 'DEBIT' }.amount.sum()", comparesEqualTo(new BigDecimal("-1242.35")))
.body("transactions.findAll { it.type == 'CREDIT' }.amount.sum()", comparesEqualTo(new BigDecimal("2650")));
}
What’s happening:
findAll { .. }.amountcollects the amounts of one type, andsum()adds them.2650has no decimals, but the sum is2650.00.comparesEqualTo(..)doesn’t mind the different scale.
Checkpoint: run the class again. Five tests pass.
Check the Net Movement
Goal: add up all six amounts exactly.
1
2
3
4
5
@Test
void theNetMovementIsExact() {
transactions(withBigDecimals())
.body("transactions.amount.sum()", comparesEqualTo(new BigDecimal("1407.65")));
}
What’s happening:
2500.00 - 42.35 - 1100.00 - 60.00 - 40.00 + 150.00is exactly1407.65.- With
BigDecimalvalues, the sum is exact. With the defaultFloatvalues, it isn’t, as you’ll see in Make a Test Fail.
Checkpoint: run the class again. Six tests pass.
A path reads from one place in the body, so it can’t add values from two top-level fields.
"balance.opening + transactions.amount.sum()"throwsThe parameter "transactions" was used but not defined. Check each value with its own path.
Compare Approximate Values
Allow a Tolerance With closeTo
Goal: check a value that’s approximate on purpose.
Not every number is money. For a measurement, such as a duration or an exchange rate from a model, a small difference is fine, and closeTo(..) allows a tolerance:
1
2
3
4
5
@Test
void closeToForValuesThatAreApproximateOnPurpose() {
transactions(transactionsApi().config(config().jsonConfig(jsonConfig().numberReturnType(NumberReturnType.DOUBLE))))
.body("transactions[1].amount", closeTo(-42.35, 0.001));
}
What’s happening:
NumberReturnType.DOUBLEreads decimals asDouble.closeTo(-42.35, 0.001)passes when the value is within0.001of-42.35.
Checkpoint: run the class again. All seven tests pass.
closeTo(..)matches onlyDoublevalues. On the defaultFloatit fails even though the value is within the tolerance:Expected: a numeric value within <0.001> of <-42.35>,Actual: <-42.35F>. SetNumberReturnType.DOUBLEfirst.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-03 -Dtest=NumbersAndMoneyTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_03.NumbersAndMoneyTest
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.463 s -- in com.javanibble.module_03.section_03.NumbersAndMoneyTest
[INFO]
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In theNetMovementIsExact, replace withBigDecimals() with transactionsApi() and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Failures:
[ERROR] NumbersAndMoneyTest.theNetMovementIsExact:98 1 expectation failed.
JSON path transactions.amount.sum() doesn't match.
Expected: a value equal to <1407.65>
Actual: <1407.650001525879>
Each Float amount was slightly off, and adding six of them made the error visible. This is the statement from the opening, and the reason money needs BigDecimal.
Change transactionsApi() back to withBigDecimals() and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected: <-42.35> but Actual: <-42.35F> | A Double was compared with the default Float | Use -42.35f, or read BigDecimal |
Expected: <1000> but Actual: <1000.00> | equalTo(..) on a BigDecimal compares the scale | Use comparesEqualTo(..) |
Actual: <1407.650001525879> for a sum | The amounts were added as Float values | Read them with NumberReturnType.BIG_DECIMAL |
Expected: a numeric value within ... but Actual: <-42.35F> | closeTo(..) was used on a Float | Set NumberReturnType.DOUBLE |
Try It Yourself
Exercise 1: Check the Groceries and the Rent
Add a test called groceriesAndRentAreExact that reads BigDecimal values and checks that the grocery amounts add up to -102.35, and that the rent amount is -1100.
Hint
Combine sumsAreExactWithBigDecimal with find { .. } from the previous sections. The rent is -1100.00, so compare it with comparesEqualTo(..).
Solution
1
2
3
4
5
6
@Test
void groceriesAndRentAreExact() {
transactions(withBigDecimals())
.body("transactions.findAll { it.category == 'GROCERIES' }.amount.sum()", comparesEqualTo(new BigDecimal("-102.35")))
.body("transactions.find { it.category == 'RENT' }.amount", comparesEqualTo(new BigDecimal("-1100")));
}
Exercise 2: Check the Whole Statement
Add a test called theStatementAddsUp that reads BigDecimal values and checks, in one chain: the opening balance is 1000 and the closing balance is 2407.65, through a root path on balance; the net movement is 1407.65; the largest amount is 2500; and the positive amounts add up to 2650.
Hint
Use rootPath("balance") and noRootPath(), as in Shorten JSON Paths With Root Paths in REST Assured. GPath has max() as well as sum(), and whole numbers are safe inside a closure.
Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void theStatementAddsUp() {
transactions(withBigDecimals())
.rootPath("balance")
.body("opening", comparesEqualTo(new BigDecimal("1000")))
.body("closing", comparesEqualTo(new BigDecimal("2407.65")))
.noRootPath()
.body("transactions.amount.sum()", comparesEqualTo(new BigDecimal("1407.65")))
.body("transactions.amount.max()", comparesEqualTo(new BigDecimal("2500")))
.body("transactions.findAll { it.amount > 0 }.amount.sum()", comparesEqualTo(new BigDecimal("2650")));
}
Summary
You built NumbersAndMoneyTest, which reads the same transactions as Integer, Float, BigDecimal and Double values, and checks counts, amounts, balances and sums with the matcher each one needs. The statement now adds up to exactly 1407.65.
- REST Assured reads whole numbers as
Integerand decimals asFloatby default. - A
Floatis fine for a quick check with thefsuffix, but it can’t hold money exactly, and its errors add up in a sum. - Set
NumberReturnType.BIG_DECIMALwithJsonConfigto read decimals exactly, and build expected values from strings. - Compare money with
comparesEqualTo(..), which ignores the scale;equalTo(..)fails on1000.00against1000. - Keep
closeTo(..), withNumberReturnType.DOUBLE, for values that are approximate on purpose.
Here are the commands you used in this guide:
1
mvn test -pl module-03 -Dtest=NumbersAndMoneyTest
What’s Next
Next: continue with Pick the Right Hamcrest Matcher in REST Assured, which picks the right matcher for each check, from hasItems and containsInAnyOrder to allOf and anyOf.
The code:
- The finished test class:
NumbersAndMoneyTest.java - The code and run commands for this module: Module 3 README
Go deeper:
- REST Assured Usage wiki, for
JsonConfigand number return types. - BigDecimal javadoc, for scale,
equals(..)andcompareTo(..).
Related guides:
- Check Every Part of an HTTP Response, where you first met the
Floatdefault. - Send Request Bodies in REST Assured, for why the Payments API sends amounts as strings instead.
