BigQuery math functions: ROUND, SAFE_DIVIDE, MOD, POW and more
The BigQuery math functions an analyst actually uses, each run on the same four-campaign table with its real result: ROUND, TRUNC, CEIL and FLOOR, why FLOAT64 rounds 2.675 down, SAFE_DIVIDE against IEEE_DIVIDE, the SAFE. prefix, MOD with negative numbers, POW, SQRT, LN and LOG argument order, GREATEST and LEAST with NULL, RANGE_BUCKET and RAND.
BigQuery’s math functions are short to write and easy to get slightly wrong. Most of them return a plausible number when something is off: a rounded value one cent away, a NULL that drops out of an average, a negative remainder. The table below lists the ones that do most of the work and the trap in each.
| Function | Returns | Watch out for |
|---|---|---|
ROUND(x, n) |
x rounded to n decimals, halves away from zero | FLOAT64 can round 2.675 to 2.67 |
TRUNC, CEIL, FLOOR |
toward zero, up, down | INT64 input comes back as FLOAT64 |
SAFE_DIVIDE(x, y) |
x / y, or NULL instead of an error | the NULL row disappears from AVG |
IEEE_DIVIDE(x, y) |
x / y as FLOAT64, never fails | returns Infinity or NaN, which spreads |
SAFE. prefix |
NULL instead of an error for most functions | only the function’s own error |
MOD(x, y) |
remainder with the sign of x | negative for negative x |
POW, SQRT, LN, LOG |
power, root, logarithms | LOG(x, base): value first, base second |
ABS, SIGN |
absolute value, -1 / 0 / 1 | |
GREATEST, LEAST |
largest / smallest across arguments | one NULL argument makes it NULL |
RANGE_BUCKET(x, array) |
the bucket x falls into | array must be sorted and of x’s type |
RAND() |
random FLOAT64 in [0, 1) | different on every run |
Note: Originally published in July 2024. Fully rewritten in October 2026: every result below was produced by running the query in BigQuery on 16 October 2026.
Two rules hold for every math function, per Google’s documentation (read in October 2026): they return NULL if any input is NULL, and NaN if any argument is NaN.
Reading to get this done?
The table used in every example
The table used in every example
Paste this before any query below and it runs as is:
WITH campaigns AS (
SELECT 'brand' AS campaign, 412.35 AS spend, 1250 AS clicks,
38 AS orders, 12 AS orders_last_week, NUMERIC '2890.50' AS revenue
UNION ALL SELECT 'search', 978.10, 2135, 41, 48, NUMERIC '3125.25'
UNION ALL SELECT 'display', 150.00, 0, 0, 2, NUMERIC '0'
UNION ALL SELECT 'retarget', 86.45, 310, 9, 9, NULL
)Four ad campaigns for one week. spend is FLOAT64 (a literal like 412.35 is a float), revenue is NUMERIC. Display has zero clicks and zero orders; retarget has no revenue recorded.
SAFE_DIVIDE and division by zero
SAFE_DIVIDE and division by zero
10 / 0 stops the query with division by zero: 10 / 0. Per-row ratios such as conversion rate and cost per order hit that the first time a campaign has no clicks. Three ways to divide:
SELECT
campaign,
ROUND(SAFE_DIVIDE(orders, clicks), 4) AS conv_rate,
ROUND(SAFE_DIVIDE(spend, orders), 2) AS cpa,
ROUND(IEEE_DIVIDE(spend, clicks), 2) AS cpc,
ROUND(SAFE_DIVIDE(revenue, spend), 2) AS roas
FROM campaigns;| campaign | conv_rate | cpa | cpc | roas |
|---|---|---|---|---|
| brand | 0.0304 | 10.85 | 0.33 | 7.01 |
| search | 0.0192 | 23.86 | 0.46 | 3.2 |
| display | NULL | NULL | Infinity | 0.0 |
| retarget | 0.029 | 9.61 | 0.28 | NULL |
SAFE_DIVIDE(x, y)is the/operator that returnsNULLinstead of failing. Display has no conversion rate and no cost per order; the query keeps running.IEEE_DIVIDE(x, y)never fails and always returns FLOAT64. It follows floating-point rules: a positive number over zero isInfinity, a negative one-Infinity, andIEEE_DIVIDE(0, 0)isNaN.IS_INFandIS_NANtest for them.- Retarget’s ROAS is NULL for a different reason: its revenue is NULL, and any NULL input gives a NULL result.
The trap is what happens after. A NULL ratio quietly leaves an average, and an Infinity poisons it:
SELECT
AVG(IEEE_DIVIDE(spend, clicks)) AS avg_cpc_ieee,
ROUND(AVG(SAFE_DIVIDE(spend, clicks)), 2) AS avg_cpc_safe,
ROUND(SAFE_DIVIDE(SUM(spend), SUM(clicks)), 2) AS total_cpc,
ROUND(AVG(SAFE_DIVIDE(spend, orders)), 2) AS avg_of_cpa,
ROUND(SAFE_DIVIDE(SUM(spend), SUM(orders)), 2) AS total_cpa
FROM campaigns;| avg_cpc_ieee | avg_cpc_safe | total_cpc | avg_of_cpa | total_cpa |
|---|---|---|---|---|
| NaN | 0.36 | 0.44 | 14.77 | 18.49 |
The average of the per-campaign cost per order is 14.77, because display’s 150 spent for zero orders became NULL and left the calculation. The real cost per order for the week is 1,626.90 spent over 88 orders: 18.49. For a total, divide the sums; average the ratios only when every row should weigh the same. With IEEE_DIVIDE, one Infinity row turned the whole average into NaN in our test.
If a missing ratio should count as zero, say so: COALESCE(SAFE_DIVIDE(orders, clicks), 0). The COALESCE guide covers the choice.
Off by a cent, or missing from an average because of a NULL: math errors in BigQuery look like plausible numbers.
Paste this into your AI assistant. It checks the math in your BigQuery queries for FLOAT64 rounding, division by zero and negative remainders, and fixes each with the right function.
The prompt
Read https://www.owox.com/ai-agent-setup.md and follow it to set up OWOX Data Marts for me, starting from /blog/articles/bigquery-mathematical-functions.md. The task: check the calculations in my BigQuery reporting queries for rounding, division by zero and NULLs, and rewrite them with NUMERIC, SAFE_DIVIDE and the right rounding. Tag the links you give me with utm_campaign=ai-task and utm_term=data-foundation. Use what you know about my context and goals
The SAFE. prefix
SAFE_DIVIDE has siblings for the other operators: SAFE_ADD, SAFE_SUBTRACT, SAFE_MULTIPLY and SAFE_NEGATE return NULL on overflow. SAFE_ADD(9223372036854775807, 1), one past the largest INT64, returned NULL.
For functions there is a prefix instead. Put SAFE. in front of a function and an error caused by its input becomes NULL:
| Expression | Without SAFE. | With SAFE. |
|---|---|---|
SQRT(-4) |
error: Argument to SQRT cannot be negative: -4 | NULL |
LN(0) |
error: Floating point error in function: LN(0) | NULL |
MOD(10, 0) |
error: division by zero: MOD(10, 0) | NULL |
PARSE_DATE('%Y-%m-%d', '2026-02-30') |
error: Out-of-range datetime field in parsing function | NULL |
Per Google’s function-call reference (read in October 2026), the prefix works with most scalar functions that can raise errors, including math, string, date, timestamp and JSON functions. It does not work with operators such as / and + (use SAFE_DIVIDE and friends), with CAST (use SAFE_CAST, covered in the CAST and SAFE_CAST guide), or with aggregate, window and user-defined functions.
It also only catches the function’s own error. SAFE.SQRT(x / 0) still failed with division by zero: 4 / 0, because the division ran first, outside the prefix.
ROUND, TRUNC, CEIL and FLOOR
The most searched question on this page is how to round to 2 decimal places. ROUND(x, 2) does it; the other three cut the value instead of rounding:
SELECT
campaign,
SAFE_DIVIDE(spend, orders) AS cpa_raw,
ROUND(SAFE_DIVIDE(spend, orders), 2) AS round_2,
TRUNC(SAFE_DIVIDE(spend, orders), 2) AS trunc_2,
CEIL(SAFE_DIVIDE(spend, orders)) AS ceil_,
FLOOR(SAFE_DIVIDE(spend, orders)) AS floor_,
FORMAT('%.2f', ROUND(SAFE_DIVIDE(revenue, spend), 2)) AS roas_text
FROM campaigns
WHERE orders > 0;| campaign | cpa_raw | round_2 | trunc_2 | ceil_ | floor_ | roas_text |
|---|---|---|---|---|---|---|
| brand | 10.851315789473684 | 10.85 | 10.85 | 11.0 | 10.0 | 7.01 |
| search | 23.856097560975609 | 23.86 | 23.85 | 24.0 | 23.0 | 3.20 |
| retarget | 9.6055555555555561 | 9.61 | 9.6 | 10.0 | 9.0 | NULL |
ROUND(x, n)rounds to n decimals. A negative n rounds left of the point:ROUND(1234.5, -2)is 1200.TRUNC(x, n)drops the digits, always toward zero: 23.856 becomes 23.85, andTRUNC(-2.7)is -2.CEILrounds up andFLOORrounds down, to a whole number. For negatives that meansCEIL(-2.7)is -2 andFLOOR(-2.3)is -3.CEILINGis the same function asCEIL. To round up or down to two decimals, scale first:CEIL(x * 100) / 100.- ROUND does not add trailing zeros. Search’s ROAS rounds to 3.2, not 3.20, because the result is a number. When a report needs two digits shown, format it:
FORMAT('%.2f', x)returned the string 3.20. - The output type follows the input, except that INT64 goes in and FLOAT64 comes out:
CEIL(5)returned 5.0.
Halves, and FLOAT64 against NUMERIC
SELECT
ROUND(2.5) AS half_up,
ROUND(-2.5) AS half_down,
ROUND(2.675, 2) AS float64_2dp,
ROUND(NUMERIC '2.675', 2) AS numeric_2dp,
ROUND(NUMERIC '2.5', 0, 'ROUND_HALF_EVEN') AS bankers_2_5,
ROUND(NUMERIC '3.5', 0, 'ROUND_HALF_EVEN') AS bankers_3_5,
ROUND(1234.5, -2) AS to_hundreds;| half_up | half_down | float64_2dp | numeric_2dp | bankers_2_5 | bankers_3_5 | to_hundreds |
|---|---|---|---|---|---|---|
| 3.0 | -3.0 | 2.67 | 2.68 | 2 | 4 | 1200.0 |
BigQuery rounds halves away from zero: 2.5 becomes 3 and -2.5 becomes -3. That is not banker’s rounding, which some other databases and Python use.
FLOAT64 cannot hold 2.675 exactly. It is stored as a number a hair below 2.675, so ROUND(2.675, 2) returns 2.67, while the same value as NUMERIC returns 2.68. ROUND(1.005, 2) gave 1.0 as a float and 1.01 as NUMERIC. The same storage issue makes 0.1 + 0.2 return 0.30000000000000004. For money, keep amounts in NUMERIC; the data types guide explains the difference.
A third argument picks the rounding mode, 'ROUND_HALF_AWAY_FROM_ZERO' (the default) or 'ROUND_HALF_EVEN', and only for NUMERIC and BIGNUMERIC. On a FLOAT64 it fails with No matching signature for function ROUND. Cast first: ROUND(CAST(x AS NUMERIC), 2, 'ROUND_HALF_EVEN').
MOD and DIV with negative numbers
MOD and DIV with negative numbers
| Expression | Result |
|---|---|
7 / 2 |
3.5 |
DIV(7, 2) |
3 |
DIV(-7, 2) |
-3 |
MOD(-7, 3) |
-1 |
MOD(7, -3) |
1 |
MOD(MOD(-7, 4) + 4, 4) |
1 |
/ on two integers returns FLOAT64 (7 / 2 is 3.5, FLOAT64); with a NUMERIC operand it returns NUMERIC (NUMERIC '7' / 2 is 3.5, NUMERIC). DIV is integer division and cuts toward zero. MOD returns the remainder with the sign of the first argument, as Google documents (read in October 2026), and fails when the divisor is 0.
The sign matters when MOD assigns buckets. Hashing a key and taking MOD(..., 10) is a common way to make a stable 10% sample, but FARM_FINGERPRINT returns negative numbers half the time:
SELECT
campaign,
orders - orders_last_week AS change,
ABS(orders - orders_last_week) AS abs_change,
SIGN(orders - orders_last_week) AS direction,
MOD(orders - orders_last_week, 4) AS mod_4,
MOD(FARM_FINGERPRINT(campaign), 10) AS hash_mod_10,
MOD(ABS(FARM_FINGERPRINT(campaign)), 10) AS bucket_0_9
FROM campaigns;| campaign | change | abs_change | direction | mod_4 | hash_mod_10 | bucket_0_9 |
|---|---|---|---|---|---|---|
| brand | 26 | 26 | 1 | 2 | 7 | 7 |
| search | -7 | 7 | -1 | -3 | 0 | 0 |
| display | -2 | 2 | -1 | -2 | -8 | 8 |
| retarget | 0 | 0 | 0 | 0 | 2 | 2 |
Display lands in bucket -8, which a filter such as BETWEEN 0 AND 9 never matches. ABS inside the MOD fixes it, as does MOD(MOD(x, n) + n, n), which gave display bucket 2. The two fixes put the row in different buckets, so pick one and keep it.
ABS and SIGN do what they say: absolute change, and -1, 0 or 1 for the direction. The one edge case Google documents is ABS on the smallest INT64, which has no positive counterpart and returns an error.
POW, SQRT, LN and LOG
SELECT
campaign,
ROUND(SQRT(SAFE_DIVIDE(cr * (1 - cr), clicks)), 4) AS cr_std_error,
ROUND(SAFE.LN(SAFE_DIVIDE(orders, orders_last_week)), 3) AS log_growth,
ROUND(LOG10(spend), 3) AS log10_spend,
ROUND(LOG(spend, 10), 3) AS log_spend_base_10,
ROUND(LOG(10, spend), 3) AS log_10_base_spend
FROM (SELECT *, SAFE_DIVIDE(orders, clicks) AS cr FROM campaigns);| campaign | cr_std_error | log_growth | log10_spend | log_spend_base_10 | log_10_base_spend |
|---|---|---|---|---|---|
| brand | 0.0049 | 1.153 | 2.615 | 2.615 | 0.382 |
| search | 0.003 | -0.158 | 2.99 | 2.99 | 0.334 |
| display | NULL | NULL | 2.176 | 2.176 | 0.46 |
| retarget | 0.0095 | 0.0 | 1.937 | 1.937 | 0.516 |
SQRTgives the standard error of a conversion rate, the usual check on whether a difference between campaigns is noise. Brand’s 3.04% is plus or minus about 0.49 points.SQRTof a negative number is an error.LNof week-over-week growth is symmetric: doubling and halving come out as the same size with opposite signs. Display went from 2 orders to 0, andLN(0)is an error, so the query usesSAFE.LN.LOG(x, base)takes the value first and the base second.LOG(spend, 10)equalsLOG10(spend). Swap them and you get the logarithm of 10 in basespend, a different number with no error. With one argument,LOG(x)is the natural logarithm, the same asLN(x).POW(x, y)(alsoPOWER) raises to a power:POW(2, 10)is 1024, and twelve months of 5% growth,POW(1.05, 12), is 1.79585632602213.POW(x, 0.5)is a square root;CBRT(-8)is -2.EXP(x)is e to the power x.
GREATEST, LEAST and RANGE_BUCKET
GREATEST, LEAST and RANGE_BUCKET
SELECT
campaign,
GREATEST(orders, orders_last_week) AS best_week,
LEAST(spend, 500) AS capped_spend,
GREATEST(revenue, 1000) AS revenue_floor,
GREATEST(COALESCE(revenue, 0), 1000) AS revenue_floor_fixed,
RANGE_BUCKET(spend, [0.0, 100, 250, 500]) AS spend_band
FROM campaigns;| campaign | best_week | capped_spend | revenue_floor | revenue_floor_fixed | spend_band |
|---|---|---|---|---|---|
| brand | 38 | 412.35 | 2890.5 | 2890.5 | 3 |
| search | 48 | 500.0 | 3125.25 | 3125.25 | 4 |
| display | 2 | 150.0 | 1000 | 1000 | 2 |
| retarget | 9 | 86.45 | NULL | 1000 | 1 |
GREATEST and LEAST compare values across columns in one row. They are not MAX and MIN, and unlike those they do not skip NULLs: retarget’s NULL revenue made the whole result NULL. Wrap the column in COALESCE when a missing value should not win. A NaN argument returns NaN. To find the largest value down a column, use MAX, covered with the other aggregate functions.
RANGE_BUCKET(x, boundaries) returns how many boundaries are less than or equal to x. With [0, 100, 250, 500], retarget’s 86.45 is in band 1, display’s 150 in band 2, brand’s 412.35 in band 3 and search’s 978.10 in band 4. A value equal to a boundary goes up: RANGE_BUCKET(250.0, [0.0, 100, 250, 500]) returned 3. It replaces a CASE ladder of WHEN spend < 100 ... lines.
Two things fail. The array type must match x: [0, 100, 250, 500] is an INT64 array and against a FLOAT64 spend gave No matching signature for function RANGE_BUCKET, which is why the first element is written 0.0. And the array must be sorted ascending with no NULL or NaN; [10, 30, 20] failed with Elements in input array to RANGE_BUCKET must be in ascending order.
RAND
RAND() returns a FLOAT64 from 0 inclusive to 1 exclusive. We generated 100,000 rows and ran the same query twice:
SELECT
COUNTIF(RAND() < 0.1) AS sampled,
ROUND(MIN(r), 6) AS min_r,
ROUND(MAX(r), 6) AS max_r,
COUNTIF(MOD(ABS(FARM_FINGERPRINT(CAST(n AS STRING))), 10) = 0) AS hash_sampled
FROM (SELECT n, RAND() AS r FROM UNNEST(GENERATE_ARRAY(1, 100000)) AS n);| run | sampled | min_r | max_r | hash_sampled |
|---|---|---|---|---|
| 1 | 10048 | 0.000015 | 0.999987 | 9946 |
| 2 | 9985 | 0.000003 | 0.999986 | 9946 |
WHERE RAND() < 0.1 keeps about 10% of rows, but a different 10% every time, so a report built on it changes on refresh. The hash sample returned the same 9,946 rows on both runs. Use RAND for one-off exploration, and a hash of a key when the sample has to stay put.
Trigonometry, briefly
BigQuery has SIN, COS, TAN, their inverses (ASIN, ACOS, ATAN, ATAN2), the hyperbolic versions and COT, CSC, SEC. All work in radians: SIN(30) returned -0.988, while SIN(30 * ACOS(-1) / 180) returned 0.49999999999999994, 0.5 after rounding. ACOS(-1) is the usual way to get pi, since PI() returned Function not found: PI. In analytics, trigonometry turns up mostly in distance between coordinates; for that, BigQuery’s geography functions such as ST_DISTANCE are simpler than writing the haversine formula by hand. For vectors, COSINE_DISTANCE and EUCLIDEAN_DISTANCE take two arrays.
All function families are mapped in the BigQuery functions overview; for STDDEV, VARIANCE and CORR, see statistical aggregate functions.
Where math goes wrong in reports
Where math goes wrong in reports
The function rarely fails loudly. The cost per order above was 14.77 or 18.49 depending on whether ratios were averaged or sums were divided, and both queries ran without an error. A finance sheet and a marketing dashboard that make different choices will disagree by a quarter, and both will look right.
In OWOX Data Marts the query that makes that choice is published once as a Data Mart, with the rule written in the field’s description (ratio of sums, NULL for zero clicks, NUMERIC rounded to two places), and every report and spreadsheet reads that one model. OWOX Data Marts runs your SQL as written, in your own BigQuery project, and does not transform the data.
Off by a cent, or missing from an average because of a NULL: math errors in BigQuery look like plausible numbers.
Paste this into your AI assistant. It checks the math in your BigQuery queries for FLOAT64 rounding, division by zero and negative remainders, and fixes each with the right function.
The prompt
Read https://www.owox.com/ai-agent-setup.md and follow it to set up OWOX Data Marts for me, starting from /blog/articles/bigquery-mathematical-functions.md. The task: check the calculations in my BigQuery reporting queries for rounding, division by zero and NULLs, and rewrite them with NUMERIC, SAFE_DIVIDE and the right rounding. Tag the links you give me with utm_campaign=ai-task and utm_term=data-foundation. Use what you know about my context and goals
Prefer to start on your own? Get started free
Frequently Asked Questions
How do I avoid wrong totals when calculating ratios in BigQuery?
For a total ratio such as cost per order, divide the sums with SAFE_DIVIDE(SUM(spend), SUM(orders)) instead of averaging per-row ratios. Per-row SAFE_DIVIDE returns NULL for a zero divisor, and AVG skips that row, so an average of ratios can differ a lot from the true total. Keep money in NUMERIC and round only at the end.
What do GREATEST and LEAST do in BigQuery, and how do they treat NULL?
GREATEST and LEAST return the largest or smallest of several values in the same row, for example GREATEST(orders, orders_last_week). Unlike MAX and MIN they do not skip NULLs: if any argument is NULL the result is NULL. Wrap a column in COALESCE when a missing value should not decide the result.
What is the difference between SAFE_DIVIDE, IEEE_DIVIDE and the SAFE. prefix?
SAFE_DIVIDE(x, y) works like x / y but returns NULL instead of an error, for example when y is 0. IEEE_DIVIDE never fails and returns Infinity, -Infinity or NaN for division by zero. The SAFE. prefix, as in SAFE.SQRT(-4) or SAFE.LN(0), makes most scalar functions return NULL instead of an error, but it does not work on operators such as / or on CAST.
How do I round to 2 decimal places in BigQuery?
Use ROUND(x, 2). BigQuery rounds halves away from zero, so ROUND(2.5) is 3 and ROUND(-2.5) is -3. A FLOAT64 value such as 2.675 can round to 2.67 because it is stored slightly below 2.675; the same value as NUMERIC rounds to 2.68. TRUNC cuts toward zero, CEIL rounds up and FLOOR rounds down.
Do BigQuery trigonometric functions use degrees or radians?
Radians. SIN, COS, TAN and their inverses take or return radians, so convert degrees by multiplying by ACOS(-1) / 180; SIN(30 * ACOS(-1) / 180) returns 0.5. BigQuery has no PI() function, which is why ACOS(-1) is the usual way to get pi.
How do LOG, LN and POW work in BigQuery?
LN(x) is the natural logarithm and LOG10(x) the base-10 logarithm. LOG(x, base) takes the value first and the base second, so LOG(100, 10) is 2 while LOG(10, 100) is 0.5. POW(x, y), also written POWER, raises x to the power y; LN and LOG fail on zero or negative values unless you use SAFE.LN or SAFE.LOG.
