Represent any floating point value as JSON.
✅ Node 18+
✅ ESM or CJS
✅ TypeScript-Native
✅ Comprehensive Documentation
✅ 100% Coverage
❤️ 🌲 Made with love in Portland, Oregon. 🌲 ❤️
npm install json-floatEmitting JSON:
import { replaceFloat, reviveFloat } from "./index.ts";
const o = {
normalFloat: 1.2,
specialFloat: Infinity,
otherValue: {
key: "string",
},
};
const s = JSON.stringify(o, replaceFloat, 2);
/*
{
"normalFloat": 1.2,
"specialFloat": {
"type": "ieee754",
"value": "Infinity"
},
"otherValue": {
"key": "string"
}
}
*/
const p = JSON.parse(s, reviveFloat); // Returns an identical objectFor more fine-grained control, see float2json,
json2float, and hasJsonRepresentation
below.
The IEEE 754 floating-point values Infinity, -Infinity, -0, and
NaN cannot be represented as a literal JSON numbers. JSON.stringify
renders the value -0 as 0 (numerically the same but with a different
byte-level representation) and renders the other three as null.
json-float converts floating point values to and from a
JSON-serializable object representation so all possible values can be
stored.
Example outputs from float2json:
{
type: 'ieee754',
value: 'NaN',
}
{
type: 'ieee754',
value: 23.56787
}
Always the string ieee754.
One of the following:
- Any of the strings
Infinity,-Infinity,-0, orNaN: represents the corresponding floating point value - A JavaScript number.
Implements the replacer interface of JSON.stringify.
Example:
const o = {
normalFloat: 1.2,
specialFloat: Infinity,
otherValue: {
key: "string",
},
};
const s = JSON.stringify(o, replaceFloat, 2);
/*
{
"normalFloat": 1.2,
"specialFloat": {
"type": "ieee754",
"value": "Infinity"
},
"otherValue": {
"key": "string"
}
}
*/Implements the reviver interface of JSON.parse.
Example:
const s = `
{
"normalFloat": 1.2,
"specialFloat": {
"type": "ieee754",
"value": "Infinity"
},
"otherValue": {
"key": "string"
}
}`;
const p = JSON.parse(s, reviveFloat);
/*
{
normalFloat: 1.2,
specialFloat: Infinity,
otherValue: {
key: 'string',
},
}
*/Example:
hasJsonRepresentation(1.1); // true
hasJsonRepresentation(NaN); // falseParameters:
- n:
number.
Returns:
true if the number can be represented directly with a JSON number, false otherwise.
Wraps a number in a JSON object.
Example:
float2json(1.1); // { type: 'ieee754', value: 1.1 }
float2json(NaN); // { type: 'ieee754', value: NaN }Parameters:
- n:
number.
Returns: JSON float object (see JSON Representation). The number is wrapped even if it could be rendered directly as a JSON number.
Unwraps a JSON float object to a number.
Example:
json2float({ type: "ieee754", value: 1.1 }); // 1.1
json2float({ type: "ieee754", value: NaN }); // NaNParameters:
- o: JSON float object (see JSON Representation).
MIT. See LICENSE.txt.
See CONTRIBUTING.