Skip to content

Commit

Permalink
Introduce a static fromNumber function to enable JavaScript sending D…
Browse files Browse the repository at this point in the history
…ecimal objects across the boundary
  • Loading branch information
ChristianIvicevic committed Oct 14, 2023
1 parent 7d90055 commit 2b7e9d9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,8 @@ libraries, this crate can be compiled with `--no-default-features`.
### `wasm-bindgen`

Enable [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) support which makes `Decimal` compatible with the
`wasm_bindgen` attribute macro and exposes a `toNumber()` method for use in JavaScript.
`wasm_bindgen` attribute macro and exposes `fromNumber()` and `toNumber()` methods to convert between `Decimal` and
the primitive `number` type across boundaries.

## Building

Expand Down
9 changes: 8 additions & 1 deletion src/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use num_traits::ToPrimitive;
use num_traits::{FromPrimitive, ToPrimitive};
use wasm_bindgen::prelude::wasm_bindgen;

use crate::Decimal;

#[wasm_bindgen]
impl Decimal {
/// Returns a new `Decimal` object instance by converting a primitive number.
#[wasm_bindgen(js_name = fromNumber)]
#[must_use]
pub fn from_number(value: f64) -> Option<Decimal> {
Decimal::from_f64(value)
}

/// Returns the value of this `Decimal` converted to a primitive number.
#[wasm_bindgen(js_name = toNumber)]
#[must_use]
Expand Down

0 comments on commit 2b7e9d9

Please sign in to comment.