Compare commits

...
Author SHA1 Message Date
ba33a71501
feat: increase PREC 512 -> 2048 2026-10-02 13:37:16 -07:00
098df2aef2
fix: ignoring decimal place accidentally 2026-10-02 13:32:53 -07:00
c745d6b5d2
feat: don't print scientific notation for n < 1000
unfortunately it isn't this easy for n > 0.001,
a similar strategy seems to prefer printing eg 1.0 * 10^-1
2026-10-02 13:22:49 -07:00
ef9d07923e
refactor: simplify raw_string creation 2026-10-02 13:09:43 -07:00
3c20174ecb
feat: prettyify scientific notation
this way it's also typst-compatible!
2026-09-30 20:10:03 -07:00
2 changed files with 28 additions and 5 deletions

View file

@ -19,10 +19,22 @@ pub fn pretty_eval(mut input: String) -> Result<String, Error> {
.is_some();
let result = nodes::eval(&input)?;
let significant_digits = get_significant_digits(&result).min(MAX_DIGITS);
let display_digits =
get_significant_digits(&result)
.min(MAX_DIGITS)
.max(if result >= 1000 || result < 1 {
1
} else if result >= 100 {
3
} else if result >= 10 {
2
// if result >= 1
} else {
1
});
Ok(format!(
"{}{}{result:.significant_digits$}{}",
"{}{}{result:.display_digits$}{}",
" ".repeat(leading_spaces),
if should_add_back_equals && should_add_back_alignment {
"& = "
@ -34,7 +46,8 @@ pub fn pretty_eval(mut input: String) -> Result<String, Error> {
""
},
if should_add_back_backslash { " \\" } else { "" }
))
)
.replace('e', " * 10^"))
}
#[test]
fn test_character_readdition() {
@ -43,9 +56,19 @@ fn test_character_readdition() {
assert_eq!(pretty_eval(" & 11".into()).unwrap(), " & 11");
assert_eq!(pretty_eval(" & 11 \\".into()).unwrap(), " & 11 \\");
}
#[test]
fn test_basic_up_to_999() {
assert_eq!(pretty_eval("1".into()).unwrap(), "1");
assert_eq!(pretty_eval("10".into()).unwrap(), "10");
assert_eq!(pretty_eval("100".into()).unwrap(), "100");
assert_eq!(pretty_eval("999".into()).unwrap(), "999");
assert_eq!(pretty_eval("1000".into()).unwrap(), "1 * 10^3");
assert_eq!(pretty_eval("11.111111".into()).unwrap(), "11.111111");
}
pub fn get_significant_digits(n: &Float) -> usize {
let raw_string: String = format!("{n}").chars().filter(|c| *c != '.').collect();
let raw_string = n.to_string().replace('.', "");
let mut consecutive_zeros = 0;
let mut consecutive_nines = 0;

View file

@ -25,7 +25,7 @@ pub fn eval(s: &str) -> Result<rug::Float, Error> {
Ok(Nodes::from_str(s)?.evaluate()?)
}
pub const PREC: u32 = 512;
pub const PREC: u32 = 2048;
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Nodes(Vec<Node>);