Skip to content

Commit

Permalink
Print large numbers accurately
Browse files Browse the repository at this point in the history
  • Loading branch information
PaddiM8 committed Mar 23, 2024
1 parent fee73e6 commit 85df4af
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion cli/src/output.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use ansi_term::Colour::Red;
use kalk::{kalk_value::ScientificNotationFormat, parser};

pub(crate) const DEFAULT_PRECISION: u32 = 63;
pub(crate) const DEFAULT_PRECISION: u32 = 1024;

pub fn eval(parser: &mut parser::Context, input: &str, precision: u32, base: u8, format: ScientificNotationFormat) {
match parser::eval(parser, input, precision) {
Expand Down
33 changes: 30 additions & 3 deletions kalk/src/kalk_value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ macro_rules! float {
macro_rules! float {
($x:expr) => {{
use rug::Float;
Float::with_val(63, $x)
Float::with_val(1024, $x)
}};
}

Expand Down Expand Up @@ -187,10 +187,10 @@ impl std::fmt::Display for KalkValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KalkValue::Number(real, imaginary, _) => {
let as_str = format_number(primitive!(real));
let as_str = format_number_big(real);

if self.has_imaginary() {
let imaginary_as_str = format_number(primitive!(imaginary).abs());
let imaginary_as_str = format_number_big(&imaginary.clone().abs());
let sign = if imaginary < &0f64 { "-" } else { "+" };

if &as_str == "0" {
Expand Down Expand Up @@ -1155,6 +1155,33 @@ pub fn format_number(input: f64) -> String {
spaced(&result)
}

#[cfg(feature = "rug")]
pub fn format_number_big(input: &Float) -> String {
let input_str = input.to_string();
let mut result = if input_str.contains('.') {
input_str
.trim_end_matches('0')
.trim_end_matches('.')
.to_string()
} else {
input_str
};

if let Some(dot_index) = result.find('.') {
let decimal_count = result.len() - dot_index;
if decimal_count > 10 {
result = result[..(result.len() - decimal_count + 10)].to_string();
}
}

spaced(&result)
}

#[cfg(not(feature = "rug"))]
pub fn format_number_big(input: f64) -> String {
format_number(input)
}

fn calculate_vector(
x: KalkValue,
y: &KalkValue,
Expand Down

0 comments on commit 85df4af

Please sign in to comment.