Added decimal -> rational parsing

This commit is contained in:
2023-04-01 14:20:11 -07:00
parent f97805b24e
commit bb48a09cc7
3 changed files with 40 additions and 9 deletions

View File

@ -101,7 +101,7 @@ impl Quantity {
}
}
pub fn float_from_string(s: &str) -> Quantity {
pub fn new_float_from_string(s: &str) -> Quantity {
let v = Float::parse(s);
return Quantity::Float {
v: Float::with_val(FLOAT_PRECISION, v.unwrap())
@ -115,6 +115,12 @@ impl Quantity {
}
}
pub fn new_rational_from_string(s: &str) -> Quantity {
return Quantity::Rational {
v: RationalQ::from_string(s)
}
}
pub fn new_rational_from_f64(f: f64) ->
Option<Quantity> {
let r = RationalQ::from_f64(f);
@ -128,6 +134,24 @@ impl Quantity {
}
}
pub fn new_rational_from_float_string(s: &str) -> Option<Quantity> {
let mut q = s.split(".");
let a = q.next().unwrap();
let b = q.next();
let b = if b.is_some() {b.unwrap()} else {""};
// Error conditions
if {
q.next().is_some() || // We should have at most one `.`
a.len() == 0 // We need something in the numerator
} { return None; }
return Some(Quantity::new_rational_from_string(
&format!("{a}{b}/1{}", "0".repeat(b.len()))
));
}
pub fn to_float(&self) -> Float {
match self {
Quantity::Float { v } => {v.clone()},