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
//! # Lotus
//! `Lotus` is a simple library to provide formatting for currency and numbers.  
//! It makes pretty printing of monetary values convinient
//!
//! # Usage
//! ```
//! # #[macro_use]
//! # use crate::Lotus::*;
//! // Builder format (recommended)
//! let rupee = LotusBuilder::default()
//!     .symbol("Rs.")
//!     .precision(1)
//!     .format_positive("%s %v")
//!     .format_negative("%s (%v)")
//!     .format_zero("%s 0.00")
//!     .decimal_str(".")
//!     .thousand_str(" ")
//!     .build()
//!     .unwrap();
//! assert_eq!("Rs. 2 000 000.0", rupee.format(2_000_000));
//! assert_eq!("Rs. (2 000.0)", rupee.format(-2000));
//! assert_eq!("Rs. 0.00", rupee.format(0));
//!
//! // Using Lotus::new()
//! let dollar = Lotus::new("$", 3); // Lotus::new(symbol, precision)
//! assert_eq!("$ 50,000.035", dollar.format(50_000.035));
//!
//! // Using lotus! macro
//! let f = lotus!(150, "$");     // lotus!(number, symbol)
//! assert_eq!("$ 150.00", f);
//! 
//! let g = lotus!(2_000_000);    // lotus!(number)
//! assert_eq!("2,000,000.00", g);
//! ```

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> {
    /// Creates a Lotus instance with the give symbol and precision
    /// and precision
    ///
    /// # Example:
    /// ```
    /// use crate::Lotus::*;
    /// let dollar = Lotus::new("$", 2);
    /// let f = dollar.format(3500);
    /// assert_eq!("$ 3,500.00", f);
    /// ```
    pub fn new(symbol: &str, precision: u8) -> Lotus {
        Lotus {
            symbol,
            precision,
            ..Default::default()
        }
    }

    /// Formats a (generic) number according to the object 
    /// configuration
    ///
    /// # Example:
    /// ```
    /// use crate::Lotus::*;
    /// let rupee = LotusBuilder::default()
    ///     .symbol("Rs.")
    ///     .precision(4)
    ///     .format_positive("%s %v")
    ///     .format_negative("%s (%v)")
    ///     .format_zero("%s 0.00")
    ///     .decimal_str(".")
    ///     .thousand_str(" ")
    ///     .build()
    ///     .unwrap();
    /// assert_eq!("Rs. 2 000 000.0000", rupee.format(2_000_000));
    /// ```
    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 --",
        }
    }
}