[READ-ONLY] Mirror of https://github.com/probablykasper/cpc. Text calculator with support for units and conversion cpc.kasper.space
calculator cli conversion converter library math package units units-converter wasm website
0

Configure Feed

Select the types of activity you want to include in your feed.

Fix units not being simplified

For example "2km/1m" and "1km/s/1m"

Kasper (Jun 30, 2026, 2:33 PM +0200) 73e3a87d a02012d8

+25
+1
CHANGELOG.md
··· 3 3 ## Next 4 4 - Add currency symbols 5 5 - Add `as` and `into` keywords for unit conversion 6 + - Fix some units not being simplified 6 7 7 8 ## 4.1.0 - 2026 Jul 29 8 9 - Add currency units
+24
src/units.rs
··· 107 107 primitives 108 108 } 109 109 110 + fn reduce_unit(number: Number) -> Number { 111 + let mut new_unit: Vec<(Unit, isize)> = Vec::new(); 112 + for (unit, exponent) in &number.unit { 113 + if unit.category() == UnitType::Temperature { 114 + new_unit.push((unit.clone(), *exponent)); 115 + continue; 116 + } 117 + let existing = new_unit 118 + .iter_mut() 119 + .find(|(u, _)| u.category() == unit.category()); 120 + if let Some(existing) = existing { 121 + existing.1 += exponent; 122 + } else { 123 + new_unit.push((unit.clone(), *exponent)) 124 + } 125 + } 126 + convert(number.clone(), new_unit).unwrap_or(number) 127 + } 128 + 110 129 // Macro for creating units. Not possible to extend/change the default units 111 130 // with this because the default units are imported into the lexer, parser 112 131 // and evaluator ··· 600 619 601 620 /// Convert a [`Number`] to a specified [`Unit`]. 602 621 pub fn convert(number: Number, to_unit: Vec<(Unit, isize)>) -> Result<Number, String> { 622 + if number.unit == to_unit { 623 + return Ok(number); 624 + } 603 625 if number.primitive_unit() != primitive_unit(&to_unit) { 604 626 return Err(format!( 605 627 "Cannot convert {} to {}", ··· 728 750 /// `Energy`, `Power`, `ElectricCurrent`, `Resistance`, and `Voltage`. 729 751 /// Other units are passed through. 730 752 pub fn to_ideal_unit(number: Number) -> Number { 753 + let number = reduce_unit(number); 731 754 let value = number.value * combined_weight(&number.unit); 732 755 let primitive = number.primitive_unit(); 733 756 if primitive == Length.primitive() { ··· 906 929 .unwrap_or(candidates[0]); 907 930 return Number::with_basic_unit(value / unit.weight(), unit); 908 931 } 932 + 909 933 number 910 934 } 911 935