Skip to content

Commit

Permalink
fixed rounding issues, eg. 9.99999997 instead of 10
Browse files Browse the repository at this point in the history
  • Loading branch information
PaddiM8 committed Dec 9, 2020
1 parent 8e3016e commit 2253fad
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
3 changes: 2 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion kalk_cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "kalk_cli"
version = "0.2.2"
version = "0.3.2"
authors = ["PaddiM8"]
edition = "2018"
readme = "../README.md"
Expand All @@ -20,3 +20,4 @@ rustyline = "6.1.2"
ansi_term = "0.12"
regex = "1"
phf = { version = "0.8", features = ["macros"] }
rug = "1.11.0"
24 changes: 15 additions & 9 deletions kalk_cli/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 { "-" };

Expand All @@ -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<char> = digits
.trim_end_matches('0')
Expand All @@ -28,16 +34,9 @@ pub fn eval(parser: &mut parser::Context, input: &str) {
.collect();
chars.insert(comma_pos, '.');
chars.into_iter().collect::<String>()
} 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!(""),
Expand Down Expand Up @@ -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()
}

0 comments on commit 2253fad

Please sign in to comment.