Crates.io | decimal-percentage |
lib.rs | decimal-percentage |
version | 0.1.4 |
source | src |
created_at | 2020-05-21 08:38:32.014865 |
updated_at | 2023-12-07 07:42:55.661679 |
description | Percentage type with rust_decimal |
homepage | |
repository | https://github.com/fMeow/decimal-percentage-rs |
max_upload_size | |
id | 244036 |
size | 16,317 |
A type to represent percentage with high precision thanks to rust_decimal
.
A percentage can perform addition, subtraction and multiplication.
use decimal_percentage::Percentage;
use rust_decimal::Decimal;
let p1 = Percentage::from(0.1f64);
let p2 = Percentage::from(0.1f32);
let p3 = Percentage::try_from("0.1").unwrap();
let p4 = Percentage::from(Decimal::from_f64(0.3).unwrap());
assert_eq!(p1 + p2, Percentage::from(0.2));
assert_eq!(p1 + 0.2, Percentage::from(0.3));
assert_eq!(p4 - p2, Percentage::from(0.2));
assert_eq!(p1 * 66.0, 6.6);
assert_eq!(p1 * 100u32, 10u32);
assert_eq!(p1 * -100i32, -10i32);
// note that a multiplication to integer type can lose precision
assert_eq!(p1 * -33i32, -3i32);
// multiplication on extremely small value with Decimal,
// that is not representable with float point
let small_value = Decimal::from_str("0.0000000000000000002").unwrap();
assert_eq!(p1 * small_value, Decimal::from_str("0.00000000000000000002").unwrap());
Contributions and feed back are welcome following Github workflow.
decimal_percentage
is provided under the MIT license. See LICENSE.