diff --git a/Cargo.lock b/Cargo.lock index e62f2fb..867f122 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -78,7 +78,7 @@ dependencies = [ [[package]] name = "typst-plugin-bigrational" -version = "0.1.0" +version = "0.1.1" dependencies = [ "num-bigint", "num-decimal", diff --git a/Cargo.toml b/Cargo.toml index fba9efe..6fcac96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "typst-plugin-bigrational" -version = "0.1.0" +version = "0.1.1" edition = "2021" [lib] diff --git a/rational.typ b/rational.typ index 3b9c6e1..5e857c3 100644 --- a/rational.typ +++ b/rational.typ @@ -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) = { @@ -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) -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs index 9f53b07..18b5902 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -198,12 +198,18 @@ fn repr(numer: &[u8], denom: &[u8]) -> Result, Box> { } #[wasm_func] -fn to_decimal_string(numer: &[u8], denom: &[u8]) -> Result, Box> { +fn to_decimal_string( + numer: &[u8], + denom: &[u8], + precision: &[u8], +) -> Result, Box> { 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]