added a rudimentary fraction representation helper

This commit is contained in:
Valerie Wolfe 2024-10-09 15:22:47 -04:00
parent ed9be1c739
commit eba5317419
3 changed files with 21 additions and 1 deletions

View file

@ -1,3 +1,4 @@
use evalexpr::{
Value,
@ -38,6 +39,25 @@ pub fn fix(arg: &Value) -> EvalResult {
} else { Err(EvalexprError::wrong_function_argument_amount(1, 2)) }
}
pub fn fraction(arg: &Value) -> EvalResult {
if let Value::Float(arg) = arg {
let mut intermediate = arg.clone();
let mut pow = 0;
while intermediate.fract() != 0_f64 {
intermediate *= 10_f64;
pow += 1;
}
let value = intermediate as i64;
let tens: i64 = 10_i64.pow(pow);
let gcd = util::gcd(value, tens);
let numerator = value / gcd;
let denominator = tens / gcd;
Ok(Value::String(format!("{numerator}/{denominator}")))
} else { Err(EvalexprError::expected_float(arg.clone())) }
}
pub fn greatest_common_divisor(arg: &Value) -> EvalResult {
if let Value::Tuple(args) = arg {
let len = args.len();

View file

@ -27,6 +27,7 @@ pub fn build(args: &mut Arguments) -> HashMapContext {
// math functions
"cos" => Function::new(|arg| helper::cosine(arg)),
"fract" => Function::new(|arg| helper::fraction(arg)),
"fix" => Function::new(|arg| helper::fix(arg)),
"gcd" => Function::new(|arg| helper::greatest_common_divisor(arg)),
"lcm" => Function::new(|arg| helper::least_common_multiple(arg)),

View file

@ -14,7 +14,6 @@ use std::{
use evalexpr::{
eval_with_context_mut,
ContextWithMutableVariables,
EvalexprError,
HashMapContext,
Value