diff --git a/Cargo.lock b/Cargo.lock index 8e91693..ba05e06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -103,12 +103,13 @@ dependencies = [ [[package]] name = "kalk_cli" -version = "0.2.2" +version = "0.3.2" dependencies = [ "ansi_term", "kalk", "phf", "regex", + "rug", "rustyline", ] diff --git a/kalk_cli/Cargo.toml b/kalk_cli/Cargo.toml index 481aba1..185914c 100644 --- a/kalk_cli/Cargo.toml +++ b/kalk_cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kalk_cli" -version = "0.2.2" +version = "0.3.2" authors = ["PaddiM8"] edition = "2018" readme = "../README.md" @@ -20,3 +20,4 @@ rustyline = "6.1.2" ansi_term = "0.12" regex = "1" phf = { version = "0.8", features = ["macros"] } +rug = "1.11.0" diff --git a/kalk_cli/src/output.rs b/kalk_cli/src/output.rs index 8857901..37649dd 100644 --- a/kalk_cli/src/output.rs +++ b/kalk_cli/src/output.rs @@ -11,6 +11,12 @@ pub fn eval(parser: &mut parser::Context, input: &str) { print_err("Too big to process."); } else { let use_sci_notation = exp > 8 || exp < -6; + + if !use_sci_notation { + println!("{}", round_value(result)); + return; + } + let comma_pos = if use_sci_notation { 1 } else { exp as usize }; let sign = if result >= 0 { "" } else { "-" }; @@ -19,7 +25,7 @@ pub fn eval(parser: &mut parser::Context, input: &str) { format!("0.{}{}", "0".repeat(exp.abs() as usize), digits) .trim_end_matches('0') .to_string() - } else if use_sci_notation || result.fract() != 0 { + } else { // Insert the comma if there are supposed to be decimals. let mut chars: Vec = digits .trim_end_matches('0') @@ -28,16 +34,9 @@ pub fn eval(parser: &mut parser::Context, input: &str) { .collect(); chars.insert(comma_pos, '.'); chars.into_iter().collect::() - } else { - // Regular number - digits[..(exp as usize)].to_string() }; - if use_sci_notation { - println!("{}{}*10^{} {}", sign, num, exp - 1, unit); - } else { - println!("{}{} {}", sign, num, unit); - } + println!("{}{}*10^{} {}", sign, num, exp - 1, unit); } } Ok(None) => print!(""), @@ -65,3 +64,10 @@ fn print_calc_err(err: CalcError) { Unknown => format!("Unknown error."), }); } + +fn round_value(value: rug::Float) -> String { + format!("{:.10}", value.to_f64_round(rug::float::Round::Down)) + .trim_end_matches('0') + .trim_end_matches('.') + .to_string() +}