Skip to content

Instantly share code, notes, and snippets.

@git314
Created April 1, 2021 12:42
Show Gist options
  • Save git314/8ab2a11c6d3aa6d36fd942318d2cdd97 to your computer and use it in GitHub Desktop.
Save git314/8ab2a11c6d3aa6d36fd942318d2cdd97 to your computer and use it in GitHub Desktop.
Format floats and strings for printing
use console::Style;
fn format_float(vec_float: Vec<Option<f64>>){
let bold = Style::new().bold();
let bright_red = Style::new().bright().red();
let bright_black = Style::new().bright().black();
println!("{}", bright_black.apply_to("<dbl>"));
for x in vec_float{
match x {
Some(i) => if i > 0.0_f64{
println!("{:.2}", bold.apply_to(i))}
else{println!("{:.2}", bright_red.apply_to(i))},
None => println!("{}", bright_red.apply_to("NA")),
}
}
}
fn format_string(vec_string: Vec<&str>, width: usize){
let bold = Style::new().bold();
let bright_black = Style::new().bright().black();
println!("{}", bright_black.apply_to("<chr>"));
for x in vec_string{
if x.len() > width {
let x = &x[0..width-1];
println!("{}{}", bold.apply_to(x), bold.apply_to('\u{2026}'))
}
else{
println!("{}", bold.apply_to(x))
}
}
}
fn main() {
let ten = 10.0_f64;
let mut a = vec![Some(ten.powf(-3.0)), Some(ten.powf(-5.0)), Some(ten.powf(-6.0)), None, Some(ten.powf(-8.0)), Some(ten.powf(-10.0))];
for f in a.iter_mut().flatten() { *f *= 123456789.0; }
let b = vec!["this", "could be a really long", "string", "tocut"];
format_float(a);
format_string(b, 6);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment