com_croftsoft_lib_string/
lib.rs

1// =============================================================================
2//! - CroftSoft String Library
3//!
4//! # Metadata
5//! - Copyright: © 2023 [`CroftSoft Inc`]
6//! - Author: [`David Wallace Croft`]
7//! - Created: 2023-11-27
8//! - Updated: 2023-11-27
9//!
10//! [`CroftSoft Inc`]: https://www.croftsoft.com/
11//! [`David Wallace Croft`]: https://www.croftsoft.com/people/david/
12// =============================================================================
13
14use std::iter::Rev;
15use std::str::Chars;
16
17pub fn to_comma_separated(value: u64) -> String {
18  let value_as_string: String = value.to_string();
19  let reversed_without_commas: Rev<Chars> = value_as_string.chars().rev();
20  let mut reversed_with_commas: String = "".to_string();
21  for (i, c) in reversed_without_commas.enumerate() {
22    if (i > 0) && (i % 3 == 0) {
23      reversed_with_commas.push(',');
24    }
25    reversed_with_commas.push(c);
26  }
27  let comma_separated: String = to_reverse_string(reversed_with_commas);
28  comma_separated
29}
30
31pub fn to_dollars(amount: f64) -> String {
32  let rounded_amount: f64 = amount.round();
33  let integer_amount: i64 = rounded_amount as i64;
34  let positive_amount: u64 = integer_amount.unsigned_abs();
35  let comma_separated_string: String = to_comma_separated(positive_amount);
36  let mut dollars: String = "".to_owned();
37  if integer_amount.is_negative() {
38    dollars.push('-');
39  }
40  dollars.push('$');
41  dollars += &comma_separated_string;
42  dollars
43}
44
45pub fn to_reverse_string(s: String) -> String {
46  s.chars().rev().collect::<String>()
47}