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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::default::Default;
use std::fmt::Display;
#[macro_use]
extern crate derive_builder;
#[macro_use]
mod macros;
mod tests;
#[derive(Debug, Builder)]
#[builder(default)]
pub struct Lotus<'a> {
symbol: &'a str,
precision: u8,
thousand_str: &'a str,
decimal_str: &'a str,
format_positive: &'a str,
format_negative: &'a str,
format_zero: &'a str
}
impl<'a> Lotus<'a> {
pub fn new(symbol: &str, precision: u8) -> Lotus {
Lotus {
symbol,
precision,
..Default::default()
}
}
pub fn format<T: Into<f64> + Display>(&self, in_number: T) -> String {
let number: f64 = in_number.into();
if number == 0. {
let value = format!("{:.*}", self.precision as usize, number);
let currencied = self.format_zero.replace("%v", value.as_str());
return currencied.replace("%s", self.symbol)
} else {
let value = format!("{:.*}", self.precision as usize, number.abs());
let mut float_iter = value.split(".");
let integral = float_iter.next().unwrap();
let fractional = float_iter.next().unwrap();
let mut formatted_integral = String::new();
for ( i, letter ) in integral.chars().rev().enumerate() {
if i % 3 == 0 && i != 0 && letter != '-' {
formatted_integral.push_str(&self.thousand_str[..]);
}
formatted_integral.push(letter);
}
let formatted_integral = formatted_integral.chars().rev().collect::<String>();
let formatted_float = format!("{}{}{}", formatted_integral, self.decimal_str, fractional);
let mut currencied = String::new();
if number.is_sign_negative() {
currencied.push_str(self.format_negative);
} else {
currencied.push_str(self.format_positive);
}
currencied = currencied.replace("%v", formatted_float.as_str());
currencied = currencied.replace("%s", &self.symbol[..]);
return currencied;
}
}
}
impl<'a> Default for Lotus<'a> {
fn default() -> Self {
Lotus {
symbol: "$",
precision: 2,
thousand_str: ",",
decimal_str: ".",
format_positive: "%s %v",
format_negative: "%s (%v)",
format_zero: "%s --",
}
}
}