Skip to content

Implementation notes

cabo edited this page May 6, 2024 · 3 revisions

Creating floating point representations

Decimal

For floating point data the algorithm https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-numeric-types-number-tostring is used, but with one modification; -0.0 is honored. [Anders Rundgren's JavaScript implementation]

Hexadecimal

Many platforms have full support for creating and ingesting hexadecimal floating point numbers. There is no indication in the encoded CBOR data item whether floating point numbers should be shown in decimal or hexadecimal; this choice typically is an option (if creating hexadecimal is provided as a choice at all).

For example, C, C++, Java, Python, Swift, Rust, D seem to come with platform support.

  • Ruby: You cannot notate hex float literals in a Ruby program, but the standard operator % (shortcut for sprintf) knows about %a:

    "%a" % 12.875
    => "0x1.9cp+3”
    "0x1.9cp3".scanf("%a")
    => [12.875]
    

    % is built-in, scanf is part of the standard library that comes with Ruby (needs “require ’scanf’” to use).

  • Python doesn't seem to have printf/scanf support (%a is used for something else), so there are extra functions:

    12.875.hex()
    '0x1.9c00000000000p+3’
    float.fromhex("0x1.9cp3")
    12.875
    

Ingesting floating point representations

Most platforms have a well-known way to ingest the form of decimal floating point numbers used by EDN. For ingesting hexadecimal floating point, see discussion about hexadecimal floating point creation above.

References

Anders Rundgren's JavaScript implementation and notes