allow decimals/floats to be formatted with precision (#449)

* allow decimals/floats to be formatted with precision

* better error message
This commit is contained in:
Darren Schroeder 2021-12-07 14:06:14 -06:00 committed by GitHub
parent 11a781fc36
commit 8d027a0617
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 2 deletions

View File

@ -216,6 +216,8 @@ fn convert_to_table(
config: &Config,
) -> Result<Option<nu_table::Table>, 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<String, ShellError> {
// vall will always be a f64 so convert it with precision formatting
let val_float = match val.trim().parse::<f64>() {
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,

View File

@ -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;
}
_ => {}
}
}