39 lines
1.2 KiB
Rust
39 lines
1.2 KiB
Rust
use rust_decimal::{Decimal, RoundingStrategy};
|
|
|
|
pub fn decimal(string_num: &String) -> Decimal {
|
|
let mut temp_num = string_num.clone();
|
|
if temp_num.contains('.') {
|
|
temp_num.remove(temp_num.find('.').unwrap());
|
|
}
|
|
let decimal_num = temp_num.parse::<i128>().unwrap();
|
|
Decimal::from_i128_with_scale(decimal_num, floating_scale(string_num))
|
|
.round_dp_with_strategy(8, RoundingStrategy::ToZero)
|
|
}
|
|
|
|
fn floating_scale(string_num: &String) -> u32 {
|
|
let temp_num = string_num.clone();
|
|
if temp_num.contains('.') {
|
|
let len = temp_num.to_string().len();
|
|
let point_index = temp_num.find('.').unwrap();
|
|
(len - (point_index + 1)) as u32
|
|
} else {
|
|
0
|
|
}
|
|
}
|
|
|
|
pub fn decimal_mul(num1: Decimal, num2: Decimal) -> Decimal {
|
|
(num1 * num2).round_dp_with_strategy(8, RoundingStrategy::ToZero)
|
|
}
|
|
|
|
pub fn decimal_add(num1: Decimal, num2: Decimal) -> Decimal {
|
|
(num1 + num2).round_dp_with_strategy(8, RoundingStrategy::ToZero)
|
|
}
|
|
|
|
pub fn decimal_sub(num1: Decimal, num2: Decimal) -> Decimal {
|
|
(num1 - num2).round_dp_with_strategy(8, RoundingStrategy::ToZero)
|
|
}
|
|
|
|
pub fn decimal_div(num1: Decimal, num2: Decimal) -> Decimal {
|
|
(num1 / num2).round_dp_with_strategy(8, RoundingStrategy::ToZero)
|
|
}
|