-
Notifications
You must be signed in to change notification settings - Fork 73
/
formatting-examples.rs
66 lines (53 loc) · 1.86 KB
/
formatting-examples.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
extern crate bigdecimal;
extern crate num_traits;
use bigdecimal::BigDecimal;
macro_rules! print_varying_values {
($fmt:literal, $exp_range:expr) => {
print_varying_values!($fmt, $exp_range, 1);
};
($fmt:literal, $exp_range:expr, $value:literal) => {
println!("{}:", $fmt);
println!("{}×", $value);
for exp in $exp_range {
let n = BigDecimal::new($value.into(), -exp);
let dec_str = format!($fmt, n);
let f = ($value as f64) * 10f64.powi(exp as i32);
let float_str = format!($fmt, f);
let s = format!("10^{}", exp);
println!("{:>7} : {:25} {}", s, dec_str, float_str);
}
println!("");
}
}
macro_rules! print_varying_formats {
($src:literal) => {
let src = $src;
let n: BigDecimal = src.parse().unwrap();
let f: f64 = src.parse().unwrap();
println!("{}", src);
println!(" {{}} : {:<15} {}", n, f);
for prec in 0..5 {
println!(" {{:.{prec}}} : {:<15.prec$} {:.prec$}", n, f, prec=prec);
}
println!("");
};
}
fn main() {
println!(" | BigDecimal | f64");
println!(" +------------ +-----");
print_varying_formats!("1234");
print_varying_formats!("1.234");
print_varying_formats!(".1234");
print_varying_formats!(".00001234");
print_varying_formats!(".00000001234");
print_varying_formats!("12340");
print_varying_formats!("1234e1");
print_varying_formats!("1234e10");
print_varying_values!("{}", -20..=20);
print_varying_values!("{:e}", -20..=20);
print_varying_values!("{:.2e}", -20..=20);
print_varying_values!("{}", -10..=10, 12345);
print_varying_values!("{:e}", -10..=10, 12345);
print_varying_values!("{:.2e}", -10..=10, 12345);
print_varying_values!("{:.3}", -10..=10, 12345);
}