Library contents

Groovy Math.toIntExact

Convert a long count to int only when its value is representable.

A simple example

Math.toIntExact

  1. Start with 7 as a long integer
  2. Do this Convert to a narrower integer
  3. Result 7
Seven is in range, so conversion preserves its value.
Lesson.groovy
println(Math.toIntExact(7L))
Output
7

Syntax

Groovy syntax
Math.toIntExact(tickets)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Fit a batch count into an integer field

A system must store a batch or grid count in a fixed-width field. Check that the calculation and the final conversion fit before committing the value to the record.

From the programlong tickets = 42000L
Result42000
Lesson.groovy
long tickets = 42000L
println(Math.toIntExact(tickets))
Output
42000

A batch of 42000 tickets fits in an int.

Advertisements

Transfer a shelf count to a label printer

The warehouse stores inventory totals as 64-bit counts. The printer accepts a signed 32-bit count and this shelf contains 650 items.

Given650
Worked result650

Using 650 gives 650 for this measurement.

Export a class attendance count

An attendance database stores row counts as long integers. The reporting form expects a signed integer and today’s total is 128.

Given128
Worked result128

Using 128 gives 128 for this measurement.

What to watch for

Casting to int can discard high bits. This conversion reports out-of-range values.

Documentation for Math.toIntExact