Skip to content

Commit f636f7b

Browse files
committed
Add toPrecision to Number
1 parent bf56d58 commit f636f7b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/js.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ extern {
213213
extern {
214214
pub type Number;
215215

216+
/// The toPrecision() method returns a string representing the Number
217+
/// object to the specified precision.
218+
///
219+
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
220+
#[wasm_bindgen(catch, method, js_name = toPrecision)]
221+
pub fn to_precision(this: &Number, precision: u8) -> Result<String, JsValue>;
222+
216223
/// The toString() method returns a string representing the
217224
/// specified Number object.
218225
///

tests/all/js_globals/Number.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,37 @@
22

33
use super::project;
44

5+
#[test]
6+
fn to_precision() {
7+
project()
8+
.file("src/lib.rs", r#"
9+
#![feature(proc_macro, wasm_custom_section)]
10+
11+
extern crate wasm_bindgen;
12+
use wasm_bindgen::prelude::*;
13+
use wasm_bindgen::js;
14+
15+
#[wasm_bindgen]
16+
pub fn to_precision(this: &js::Number, precision: u8) -> String {
17+
let result = this.to_precision(precision);
18+
let result = match result {
19+
Ok(num) => num,
20+
Err(_err) => "RangeError".to_string()
21+
};
22+
result
23+
}
24+
"#)
25+
.file("test.ts", r#"
26+
import * as assert from "assert";
27+
import * as wasm from "./out";
28+
29+
export function test() {
30+
assert.equal(wasm.to_precision(0.1, 3), "0.100");
31+
assert.equal(wasm.to_precision(10, 101), "RangeError");
32+
}
33+
"#)
34+
.test()
35+
}
536

637
#[test]
738
fn to_string() {

0 commit comments

Comments
 (0)