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 06c388a
Show file tree
Hide file tree
Showing 21 changed files with 36 additions and 0 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 = &args[1];
let precision = if precision.is_undefined() {
0
} else {
assert_arg!(precision.is_integer(), context, 2);
precision.as_isize()
};

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

0 comments on commit 06c388a

Please sign in to comment.