From 2b7e9d97db5c399c3ca1ee636750fc0a248a4115 Mon Sep 17 00:00:00 2001 From: Christian Ivicevic Date: Sat, 14 Oct 2023 11:40:04 +0200 Subject: [PATCH] Introduce a static fromNumber function to enable JavaScript sending Decimal objects across the boundary --- README.md | 3 ++- src/wasm.rs | 9 ++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) 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]