Skip to content

Commit

Permalink
Add ability to specify precision for decimal string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
DanikVitek committed Oct 25, 2024
1 parent f872231 commit 27277a7
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "typst-plugin-bigrational"
version = "0.1.0"
version = "0.1.1"
edition = "2021"

[lib]
Expand Down
14 changes: 9 additions & 5 deletions rational.typ
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,17 @@
}
}

#let to-decimal-str(x) = {
#let to-decimal-str(x, precision: 8) = {
let (numer, denom) = rational(x)
str(p.to_decimal_string(bytes(numer), bytes(denom)))
str(p.to_decimal_string(bytes(numer), bytes(denom), int.to-bytes(precision)))
}

#let to-float(x) = {
float(to-decimal-str(x))
#let to-float(x, precision: 8) = {
float(to-decimal-str(x, precision: precision))
}

#let to-decimal(x, precision: 8) = {
decimal(to-decimal-str(x, precision: precision))
}

#let abs-diff(a, b) = {
Expand All @@ -142,4 +146,4 @@
let ordering-bytes = p.cmp(bytes(a-numer), bytes(a-denom), bytes(b-numer), bytes(b-denom))

int.from-bytes(ordering-bytes)
}
}
10 changes: 8 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,18 @@ fn repr(numer: &[u8], denom: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
}

#[wasm_func]
fn to_decimal_string(numer: &[u8], denom: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> {
fn to_decimal_string(
numer: &[u8],
denom: &[u8],
precision: &[u8],
) -> Result<Vec<u8>, Box<dyn Error>> {
let numer: BigInt = str::from_utf8(numer)?.parse()?;
let denom: BigInt = str::from_utf8(denom)?.parse()?;
let value = BigDecimal::new(numer, denom);

Ok(value.to_string().into_bytes())
let precision = usize::try_from(i64::from_le_bytes(precision.try_into()?))?;

Ok(format!("{value:#.precision$}").into_bytes())
}

#[wasm_func]
Expand Down

0 comments on commit 27277a7

Please sign in to comment.