Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bps conversion to Decimal and Decimal256 #1715

Merged
merged 5 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/std/src/math/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ impl Decimal {
Self(((x as u128) * 1_000_000_000_000_000).into())
}

/// Convert bps (basis points) into Decimal
shanev marked this conversation as resolved.
Show resolved Hide resolved
pub fn bps(x: u64) -> Self {
Self(((x as u128) * 100_000_000_000_000).into())
}

/// Creates a decimal from a number of atomic units and the number
/// of decimal places. The inputs will be converted internally to form
/// a decimal with 18 decimal places. So the input 123 and 2 will create
Expand Down Expand Up @@ -768,6 +773,12 @@ mod tests {
assert_eq!(value.0, Decimal::DECIMAL_FRACTIONAL / Uint128::from(8u8));
}

#[test]
fn decimal_bps() {
let value = Decimal::bps(125);
assert_eq!(value.0, Decimal::DECIMAL_FRACTIONAL / Uint128::from(80u8));
}

#[test]
fn decimal_from_atomics_works() {
let one = Decimal::one();
Expand Down
14 changes: 14 additions & 0 deletions packages/std/src/math/decimal256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ impl Decimal256 {
Self(Uint256::from(x) * Uint256::from(1_000_000_000_000_000u128))
}

/// Convert bps (basis points) into Decimal256
shanev marked this conversation as resolved.
Show resolved Hide resolved
pub fn bps(x: u64) -> Self {
Self(Uint256::from(x) * Uint256::from(100_000_000_000_000u128))
}

/// Creates a decimal from a number of atomic units and the number
/// of decimal places. The inputs will be converted internally to form
/// a decimal with 18 decimal places. So the input 123 and 2 will create
Expand Down Expand Up @@ -794,6 +799,15 @@ mod tests {
assert_eq!(value.0, Decimal256::DECIMAL_FRACTIONAL / Uint256::from(8u8));
}

#[test]
fn decimal256_bps() {
let value = Decimal256::bps(125);
assert_eq!(
value.0,
Decimal256::DECIMAL_FRACTIONAL / Uint256::from(80u8)
);
}

#[test]
fn decimal256_from_atomics_works() {
let one = Decimal256::one();
Expand Down