MCPcopy Create free account
hub / github.com/apache/datafusion / round_integer

Function round_integer

datafusion/spark/src/function/math/round.rs:236–276  ·  view source on GitHub ↗

Round an integer value to the given scale using HALF_UP rounding mode. Only meaningful when `scale` is negative — a non-negative scale leaves the integer unchanged because integers have no fractional part. This matches Spark's `RoundBase` behaviour for `ByteType`, `ShortType`, `IntegerType`, and `LongType`, which round to the nearest power-of-ten boundary and return the same integer type. In AN

(value: i64, scale: i32, enable_ansi_mode: bool)

Source from the content-addressed store, hash-verified

234/// round_integer(42, -10, false) → Ok(0) // factor overflows → 0
235/// ```
236fn round_integer(value: i64, scale: i32, enable_ansi_mode: bool) -> Result<i64> {
237 if scale >= 0 {
238 return Ok(value);
239 }
240 let abs_scale = (-scale) as u32;
241 let Some(factor) = 10_i64.checked_pow(abs_scale) else {
242 return Ok(0);
243 };
244 let remainder = value % factor;
245 let threshold = factor / 2;
246 let result = if remainder >= threshold {
247 if enable_ansi_mode {
248 value
249 .checked_sub(remainder)
250 .and_then(|v| v.checked_add(factor))
251 .ok_or_else(|| {
252 (exec_err!("Int64 overflow on round({value}, {scale})")
253 as Result<(), _>)
254 .unwrap_err()
255 })?
256 } else {
257 value.wrapping_sub(remainder).wrapping_add(factor)
258 }
259 } else if remainder <= -threshold {
260 if enable_ansi_mode {
261 value
262 .checked_sub(remainder)
263 .and_then(|v| v.checked_sub(factor))
264 .ok_or_else(|| {
265 (exec_err!("Int64 overflow on round({value}, {scale})")
266 as Result<(), _>)
267 .unwrap_err()
268 })?
269 } else {
270 value.wrapping_sub(remainder).wrapping_sub(factor)
271 }
272 } else {
273 value - remainder
274 };
275 Ok(result)
276}
277
278// ---------------------------------------------------------------------------
279// Decimal rounding using ArrowNativeTypeOp (HALF_UP)

Callers 1

spark_roundFunction · 0.85

Calls 1

unwrap_errMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…