diff --git a/crates/nu-command/src/viewers/table.rs b/crates/nu-command/src/viewers/table.rs index 29da046396..b6b6f2dc23 100644 --- a/crates/nu-command/src/viewers/table.rs +++ b/crates/nu-command/src/viewers/table.rs @@ -216,6 +216,8 @@ fn convert_to_table( config: &Config, ) -> Result, ShellError> { let mut iter = iter.into_iter().peekable(); + let color_hm = get_color_config(config); + let float_precision = config.float_precision as usize; if let Some(first) = iter.peek() { let mut headers = first.columns(); @@ -268,7 +270,6 @@ fn convert_to_table( data.push(row); } - let color_hm = get_color_config(config); Ok(Some(nu_table::Table { headers: headers .into_iter() @@ -294,6 +295,17 @@ fn convert_to_table( color_style: Some(color_hm["row_index"]), }, } + } else if &y.0 == "float" { + // set dynamic precision from config + let precise_number = + match convert_with_precision(&y.1, float_precision) { + Ok(num) => num, + Err(e) => e.to_string(), + }; + StyledString { + contents: precise_number, + style: style_primitive(&y.0, &color_hm), + } } else { StyledString { contents: y.1, @@ -311,6 +323,20 @@ fn convert_to_table( } } +fn convert_with_precision(val: &str, precision: usize) -> Result { + // vall will always be a f64 so convert it with precision formatting + let val_float = match val.trim().parse::() { + Ok(f) => f, + Err(e) => { + return Err(ShellError::LabeledError( + format!("error converting string [{}] to f64", &val), + e.to_string(), + )); + } + }; + Ok(format!("{:.prec$}", val_float, prec = precision)) +} + struct PagingTableCreator { head: Span, stream: ValueStream, diff --git a/crates/nu-protocol/src/config.rs b/crates/nu-protocol/src/config.rs index 241c35a9d7..fbbc488859 100644 --- a/crates/nu-protocol/src/config.rs +++ b/crates/nu-protocol/src/config.rs @@ -13,6 +13,7 @@ pub struct Config { pub use_grid_icons: bool, pub footer_mode: FooterMode, pub animate_prompt: bool, + pub float_precision: i64, } impl Default for Config { @@ -25,6 +26,7 @@ impl Default for Config { use_grid_icons: false, footer_mode: FooterMode::Never, animate_prompt: ANIMATE_PROMPT_DEFAULT, + float_precision: 4, } } } @@ -83,9 +85,12 @@ impl Value { } "animate_prompt" => { let val = value.as_bool()?; - config.animate_prompt = val; } + "float_precision" => { + let val = value.as_integer()?; + config.float_precision = val; + } _ => {} } }