From 5b9e9849e8d2ccc54d798d2c4c65d58736262e12 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Sat, 6 Jun 2020 14:55:30 +0200 Subject: [PATCH] Improved output. --- kalk_cli/src/output.rs | 46 +++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/kalk_cli/src/output.rs b/kalk_cli/src/output.rs index d080061..3787e73 100644 --- a/kalk_cli/src/output.rs +++ b/kalk_cli/src/output.rs @@ -4,28 +4,36 @@ use kalk::parser::{self}; pub fn eval(parser: &mut parser::Context, input: &str) { match parser::parse(parser, input, 53) { Ok(Some(result)) => { + let (_, digits, exp_option) = result.to_sign_string_exp(10, None); + let exp = if let Some(exp) = exp_option { exp } else { 0 }; + if result.is_infinite() { err("Too big to process."); - } else if result > 100_000_000 || result < -100_000_00 { - let sign = if result >= 0 { "" } else { "-" }; - let (_, digits, exp) = result.to_sign_string_exp(10, None); - let value = format!( - "{}.{}", - digits[0..1].to_string(), - digits[1..].to_string().trim_end_matches('0') - ); - - println!("{}{}*10^{}", sign, value, exp.unwrap() - 1); - } else if result.clone().fract() == 0 { - println!("{}", result.to_integer().unwrap()); + /*} else if result.clone().fract() == 0 { + println!("{}", result.to_integer().unwrap());*/ } else { - println!( - "{}", - result - .to_string() - .trim_end_matches('0') - .trim_end_matches('.') - ); + let use_sci_notation = exp > 8 || exp < -6; + let comma_pos = if use_sci_notation { 1 } else { exp as usize }; + let sign = if result >= 0 { "" } else { "-" }; + + let num = if use_sci_notation { + // Insert the comma if there are supposed to be decimals. + let mut chars: Vec = digits.trim_end_matches('0').chars().collect(); + chars.insert(comma_pos, '.'); + chars.into_iter().collect::() + } else if exp < 0 { + // 0 < x < 1 + format!("0.{}{}", "0".repeat(exp.abs() as usize), digits) + } else { + // Regular number + digits[..(exp as usize)].to_string() + }; + + if use_sci_notation { + println!("{}{}*10^{}", sign, num, exp); + } else { + println!("{}{}", sign, num); + } } } Ok(None) => print!(""),