diff --git a/README.md b/README.md index 29a14bb..fe6675a 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/wasm.rs b/src/wasm.rs index cc6f251..2308354 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -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::from_f64(value) + } + /// Returns the value of this `Decimal` converted to a primitive number. #[wasm_bindgen(js_name = toNumber)] #[must_use]