How LosslessNumbers work
mainBy default, numeric values are parsed into a LosslessNumber class. This class stores the value as a string to prevent precision loss.
- You can perform regular numeric operations with a
LosslessNumber(e.g.,json.number + 2). - You can check if a value is a lossless number using the
.isLosslessNumberproperty. - You can convert it to a native number using
.valueOf(). - Warning: Converting a
LosslessNumberto a nativenumberwill throw an error if the conversion would result in information loss (truncation, overflow, or underflow).
import { parse } from 'lossless-json'
const text = '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}'
const json = parse(text)
console.log(json.normal.isLosslessNumber) // true
console.log(json.normal.valueOf()) // number, 2.3
// LosslessNumbers can be used as regular numbers
console.log(json.normal + 2) // number, 4.3
// This will throw an error because it would lose information:
console.log(json.long + 1)
// throws Error: Cannot safely convert LosslessNumber to number...