FAQ - Help and questions

How do JavaScript numbers, JSON and BigInt map to Rust integer and float types?

#porting#javascript#integerspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Every JavaScript number is a 64-bit float, exact for integers only up to 2 to the power 53 minus 1. A Rust port must pick i64, u64 or f64 for each field. Large identifiers in JSON can lose digits in JavaScript but stay exact in Rust when parsed into u64, so compare both sides on the same data.

Checked with rustc 1.93.0, serde 1.0.229, serde_json 1.0.154, Node.js v22.19.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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):

javascript
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); }
text
9007199254740992
false
9007199254740991
0.30000000000000004
true
9007199254740993n
Do not know how to serialize a BigInt

The 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:

src/main.rsrust
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()));
}
text
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#

  1. For each numeric field in the JavaScript or TypeScript code, decide what it is: a count or index (usize or u32), an identifier (u64, or better a string), an amount of money (an integer count of the smallest unit, not a float), a measurement (f64).
  2. 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 9007199254740993 as a number hands the browser a different number.
  3. Use u64 or i64 in Rust for identifiers, with serde's #[serde(with = ...)] or a string field if they must be strings in JSON.
  4. 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 f64 results that came from different operation orders.
  5. 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 f64 for identifiers or money because that is what JavaScript did.
  • Letting a Rust i64 that exceeds 2^53 flow into a JavaScript client as a JSON number.
  • Treating NaN and Infinity as ordinary values in JSON. They are not valid JSON; check what your serialiser does.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet