| Crates.io | mathengine |
| lib.rs | mathengine |
| version | 0.1.0 |
| created_at | 2025-10-06 23:48:57.154383+00 |
| updated_at | 2025-10-06 23:48:57.154383+00 |
| description | Complete mathematical expression evaluator with unit conversions |
| homepage | https://github.com/javif89/mathengine |
| repository | https://github.com/javif89/mathengine |
| max_upload_size | |
| id | 1871007 |
| size | 10,093 |
A complete mathematical expression evaluator with comprehensive unit conversion support.
+, -, *, /, ^ with proper precedenceValue types, not stringsuse mathengine::{evaluate_expression, Value};
fn main() -> Result<(), mathengine::Error> {
// Simple arithmetic
let result = evaluate_expression("2 + 3 * 4")?;
println!("Result: {}", result); // Result: 14
// Unit conversions
let result = evaluate_expression("10m to feet")?;
println!("Result: {}", result); // Result: 32.808ft
// Complex expressions
let result = evaluate_expression("(100F - 32) * 5/9")?;
println!("Result: {}", result); // Result: 37.778
Ok(())
}
The library returns a Value enum that can be pattern matched:
use mathengine::{evaluate_expression, Value, Number, UnitValue};
match evaluate_expression("10m + 5")? {
Value::Number(n) => {
println!("Plain number: {}", n);
}
Value::UnitValue(uv) => {
println!("Value with unit: {}", uv);
// Access the raw value if needed
// let raw = uv.value();
}
}
The library provides detailed error information:
use mathengine::{evaluate_expression, Error};
match evaluate_expression("2 / 0") {
Ok(value) => println!("Result: {}", value),
Err(Error::Lexer(e)) => eprintln!("Tokenization failed: {}", e),
Err(Error::Parser(e)) => eprintln!("Parsing failed: {}", e),
Err(Error::Evaluator(e)) => eprintln!("Evaluation failed: {}", e),
}
2 + 35 - 23 * 48 / 22^32 * (3 + 4)m, cm, mm, km, ft, in, yd, miC, F, K10m to feet, 23C to F10m + 5 (adds 5 meters)10ft * 2 (multiplies by scalar)100cm - 1m (automatic conversion)For more control, you can use the individual components:
use mathengine_lexer::Lexer;
use mathengine_parser::Parser;
use mathengine_evaluator::evaluate;
// Manual pipeline
let tokens = Lexer::new("2 + 3").tokenize()?;
let ast = Parser::new(tokens).parse()?;
let result = evaluate(&ast)?;
This is the main crate that ties together:
mathengine-lexer: Tokenizationmathengine-parser: AST generationmathengine-evaluator: Expression evaluationmathengine-units: Unit conversion systemYou can also use these crates individually for more fine-grained control.
Licensed under either of Apache License, Version 2.0 or MIT license at your option.