Skip to content

Commit

Permalink
feat: add $round function
Browse files Browse the repository at this point in the history
  • Loading branch information
nated0g committed Sep 4, 2024
1 parent 1d98acc commit 36ac751
Show file tree
Hide file tree
Showing 22 changed files with 42 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ Cargo.lock
.vscode
.nvimrc
.data
.idea
34 changes: 34 additions & 0 deletions src/evaluator/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1201,3 +1201,37 @@ pub fn fn_base64_decode<'a>(

Ok(Value::string(context.arena, &decoded))
}

pub fn fn_round<'a>(
context: FunctionContext<'a, '_>,
args: &[&'a Value<'a>],
) -> Result<&'a Value<'a>> {
max_args!(context, args, 2);
let number = &args[0];
if number.is_undefined() {
return Ok(Value::undefined());
}
assert_arg!(number.is_number(), context, 1);

let precision = if let Some(precision) = args.get(1) {
assert_arg!(precision.is_integer(), context, 2);
precision.as_isize()
} else {
0
};

let num = multiply_by_pow10(number.as_f64(), precision)?;
let num = num.round_ties_even();
let num = multiply_by_pow10(num, -precision)?;

Ok(Value::number(context.arena, num))
}

// We need to do this multiplication by powers of 10 in a string to avoid
// floating point precision errors which will affect the rounding algorithm
fn multiply_by_pow10(num: f64, pow: isize) -> Result<f64> {
let num_str = format!("{}e{}", num, pow);
num_str
.parse::<f64>()
.map_err(|e| Error::D3137Error(e.to_string()))
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ impl<'a> JsonAta<'a> {
bind_native!("power", 2, fn_power);
bind_native!("replace", 4, fn_replace);
bind_native!("reverse", 1, fn_reverse);
bind_native!("round", 2, fn_round);
bind_native!("sort", 2, fn_sort);
bind_native!("split", 3, fn_split);
bind_native!("sqrt", 1, fn_sqrt);
Expand Down
6 changes: 6 additions & 0 deletions tests/testsuite/groups/function-round/case012.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"expr": "$round(4.515, 2)",
"dataset": null,
"bindings": {},
"result": 4.52
}
6 changes: 0 additions & 6 deletions tests/testsuite/skip/function-round/case012.json

This file was deleted.

0 comments on commit 36ac751

Please sign in to comment.