| 1 | use alloc::string::String; |
| 2 | use core::str::FromStr; |
| 3 | |
| 4 | use num_traits::{FromPrimitive, ToPrimitive}; |
| 5 | use wasm_bindgen::prelude::*; |
| 6 | |
| 7 | use crate::Decimal; |
| 8 | |
| 9 | #[wasm_bindgen] |
| 10 | impl Decimal { |
| 11 | /// Returns a new `Decimal` object instance by converting a primitive number. |
| 12 | /// |
| 13 | /// Returns `undefined` in JavaScript if the value cannot be represented as a `Decimal` |
| 14 | /// (e.g. `NaN`, `Infinity`, or `-Infinity`). |
| 15 | #[wasm_bindgen(js_name = fromNumber)] |
| 16 | #[must_use] |
| 17 | pub fn from_number(value: f64) -> Option<Decimal> { |
| 18 | Decimal::from_f64(value) |
| 19 | } |
| 20 | |
| 21 | /// Returns a new `Decimal` object instance by parsing a string representation. |
| 22 | /// |
| 23 | /// Returns `undefined` in JavaScript if the string cannot be parsed as a valid `Decimal`. |
| 24 | #[wasm_bindgen(js_name = fromString)] |
| 25 | #[must_use] |
| 26 | pub fn from_string(value: &str) -> Option<Decimal> { |
| 27 | Decimal::from_str(value).ok() |
| 28 | } |
| 29 | |
| 30 | /// Returns the value of this `Decimal` converted to a primitive number. |
| 31 | /// |
| 32 | /// # Note |
| 33 | /// At the time of writing, the conversion from `Decimal` to `f64` cannot fail. To guard |
| 34 | /// against future implementation changes, `f64::NAN` is returned as a fallback value. |
| 35 | #[wasm_bindgen(js_name = toNumber)] |
| 36 | #[must_use] |
| 37 | pub fn to_number(&self) -> f64 { |
| 38 | self.to_f64().unwrap_or(f64::NAN) |
| 39 | } |
| 40 | |
| 41 | /// Returns the string representation of this `Decimal`. |
| 42 | /// |
| 43 | /// This intentionally overrides the default JS `toString()` so that string coercion |
| 44 | /// (e.g. template literals, `console.log`) produces the decimal representation. |
| 45 | #[wasm_bindgen(js_name = toString)] |
| 46 | #[must_use] |
| 47 | pub fn to_string_js(&self) -> String { |
| 48 | self.to_string() |
| 49 | } |
| 50 | } |