refactor(formatting): use pre-stringified value

This commit is contained in:
electria 2026-11-15 20:11:13 -08:00
commit 3073205d90
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs

View file

@ -1,5 +1,3 @@
use rug::Float;
use crate::nodes::{self, Error}; use crate::nodes::{self, Error};
pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> { pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> {
@ -11,7 +9,7 @@ pub fn pretty_eval(input: &str, max_digits: usize) -> Result<String, Error> {
let should_add_back_backslash = input.contains('\\'); let should_add_back_backslash = input.contains('\\');
let result = nodes::eval(&input)?; let result = nodes::eval(&input)?;
let display_digits = get_significant_digits(&result).clamp( let display_digits = get_significant_digits(result.to_string()).clamp(
if result >= 1000 || result < 1 { if result >= 1000 || result < 1 {
1 1
} else if result >= 100 { } else if result >= 100 {
@ -46,8 +44,8 @@ impl StrExt for str {
} }
} }
pub fn get_significant_digits(n: &Float) -> usize { pub fn get_significant_digits(n: impl AsRef<str>) -> usize {
let raw_string = n.to_string().replace(['.', '-'], ""); let raw_string = n.as_ref().replace(['.', '-'], "");
let mut consecutive_zeros = 0; let mut consecutive_zeros = 0;
let mut consecutive_nines = 0; let mut consecutive_nines = 0;
@ -82,7 +80,7 @@ pub fn get_significant_digits(n: &Float) -> usize {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
fn eval(s: &str) -> Float { fn eval(s: &str) -> rug::Float {
crate::nodes::eval(s).unwrap() crate::nodes::eval(s).unwrap()
} }
macro_rules! assert_pretty_eval { macro_rules! assert_pretty_eval {
@ -151,9 +149,9 @@ mod tests {
let test_4 = eval("12.0096 + 1.00784 * 3 + 12.0096 + 1.00784 * 2 + 15.9994 + 1.00784"); let test_4 = eval("12.0096 + 1.00784 * 3 + 12.0096 + 1.00784 * 2 + 15.9994 + 1.00784");
assert_eq!(test_4.to_f64(), 46.06564); assert_eq!(test_4.to_f64(), 46.06564);
assert_eq!(get_significant_digits(&many_zeros), 8); assert_eq!(get_significant_digits(many_zeros.to_string()), 8);
assert_eq!(get_significant_digits(&many_nines), 6); assert_eq!(get_significant_digits(many_nines.to_string()), 6);
assert_eq!(get_significant_digits(&zero_nine_zero), 6); assert_eq!(get_significant_digits(zero_nine_zero.to_string()), 6);
assert_eq!(get_significant_digits(&test_4), 7); assert_eq!(get_significant_digits(test_4.to_string()), 7);
} }
} }