Answer#
JavaScript has one number type, Number, an IEEE 754 double. Integers between -(2^53 - 1) and 2^53 - 1 are exact (Number.MAX_SAFE_INTEGER is 9007199254740991). Above that, neighbouring integers cannot all be represented, so adding 1 may do nothing. BigInt is a separate type for arbitrary-size integers, and JSON.stringify refuses to serialise one.
Rust makes the choice per field: i32, i64, u64, f64 and so on. In a port, look at what each number means (a count, an identifier, money, a measurement) and choose the type from that, not from the fact that JavaScript used Number for everything.
Node.js (v22.19.0):
const text = '{"id": 9007199254740993, "price": 0.1}';
const v = JSON.parse(text);
console.log(v.id);
console.log(Number.isSafeInteger(9007199254740993));
console.log(Number.MAX_SAFE_INTEGER);
console.log(0.1 + 0.2);
console.log(2 ** 64 === 2 ** 64 + 1);
console.log(9007199254740993n);
try { JSON.stringify({ id: 9007199254740993n }); } catch (e) { console.log(e.message); }9007199254740992
false
9007199254740991
0.30000000000000004
true
9007199254740993n
Do not know how to serialize a BigIntThe identifier ...993 in the JSON text came back as ...992: the JavaScript parser had to round it. The same text in Rust (rustc 1.93.0, serde_json 1.0.154), where the choice of type decides what you get:
use serde_json::Value;
fn main() {
let text = r#"{"id": 9007199254740993, "price": 0.1}"#;
let v: Value = serde_json::from_str(text).unwrap();
let id = &v["id"];
println!("as u64: {:?}", id.as_u64());
println!("as f64: {:?}", id.as_f64());
println!("{}", 9007199254740993u64 as f64 as u64);
println!("{}", 0.1 + 0.2);
println!("{:?}", (u64::MAX as f64) as u64 == u64::MAX);
// a typed field makes the choice explicit
#[derive(Debug, serde::Deserialize)]
struct Row { id: u64 }
let r: Row = serde_json::from_str(text).unwrap();
println!("typed id {}", r.id);
println!("{:?}", serde_json::from_str::<Row>(r#"{"id": -1}"#).map_err(|e| e.to_string()));
}as u64: Some(9007199254740993)
as f64: Some(9007199254740992.0)
9007199254740992
0.30000000000000004
true
typed id 9007199254740993
Err("invalid value: integer `-1`, expected u64 at line 1 column 9")Reading it: serde_json keeps the digits as an integer, so as_u64 gives the exact ...993, while converting through f64 rounds exactly as JavaScript did. 0.1 + 0.2 is the same in both languages, because both use the same double format. A typed u64 field also rejects a negative number, where JavaScript accepts anything.
How to do it#
- For each numeric field in the JavaScript or TypeScript code, decide what it is: a count or index (
usizeoru32), an identifier (u64, or better a string), an amount of money (an integer count of the smallest unit, not a float), a measurement (f64). - If a JSON producer or consumer still runs in JavaScript, make sure large identifiers travel as strings, because the JavaScript side will round numbers above 2^53. A Rust server that sends
9007199254740993as a number hands the browser a different number. - Use
u64ori64in Rust for identifiers, with serde's#[serde(with = ...)]or a string field if they must be strings in JSON. - When comparing results of the old and the new code, compare numbers as the type you chose, not as formatted text, and use a tolerance for
f64results that came from different operation orders. - Port bitwise operators with care: in JavaScript
|,&and<<convert to 32-bit signed integers first. In Rust the operand type decides (i32,u32,u64), with no hidden conversion.
Common mistakes#
- Using
f64for identifiers or money because that is what JavaScript did. - Letting a Rust
i64that exceeds 2^53 flow into a JavaScript client as a JSON number. - Treating
NaNandInfinityas ordinary values in JSON. They are not valid JSON; check what your serialiser does.
Related questions#
Is there a Rust type like BigInt?#
Not in the standard library for arbitrary size. There are crates for big integers; for values that fit in 128 bits, i128 and u128 exist. None of them was run for this thread.
Why does 0.1 + 0.2 print the same digits in both?#
Both languages print the shortest text that identifies the double. The value is the same in both; it is a property of binary floating point, not of either language.
Sources#
- MDN, "Number.MAX_SAFE_INTEGER": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
serde_json::Number: https://docs.rs/serde_json/latest/serde_json/struct.Number.html