Skip to content

Commit

Permalink
better error handling in calculator widget
Browse files Browse the repository at this point in the history
  • Loading branch information
mikkeldenker committed Feb 28, 2024
1 parent d9b7328 commit 5c7278a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
19 changes: 10 additions & 9 deletions crates/core/src/widgets/calculator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,21 +191,22 @@ impl Calculator {
return Err(Error::CalculatorParse);
}

let result: String = res
.get_main_result_spans()
.map(|span| match span.kind() {
let mut result: String = String::new();

for span in res.get_main_result_spans() {
match span.kind() {
fend_core::SpanKind::Number => {
let num = span.string().parse::<f64>().unwrap();
let num = span.string().parse::<f64>()?;

if num.fract() > 0.01 {
format!("{:.2}", num)
result.push_str(format!("{:.2}", num).as_str());
} else {
num.to_string()
result.push_str(num.to_string().as_str());
}
}
_ => span.string().to_string(),
})
.collect();
_ => result.push_str(span.string()),
}
}

Ok(Calculation {
input: expr.to_string(),
Expand Down
3 changes: 3 additions & 0 deletions crates/core/src/widgets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub mod thesaurus;
pub enum Error {
#[error("Calculator parse")]
CalculatorParse,

#[error("Failed to parse float")]
FloatParse(#[from] std::num::ParseFloatError),
}

pub struct Widgets {
Expand Down

0 comments on commit 5c7278a

Please sign in to comment.