title: Serialise BigDecimal, BigNumber, BigInt etc. to and from JSON
body: <p>What types, and what serialisation pattern, can I use to ensure I have <strong>arbitrary-precision numbers</strong> in my JavaScript program while it's running, but the <strong>state is serialised to / deserialised from JSON</strong> with a minimum of pain?</p>
  
  <p>I am writing an application that makes heavy use of numbers with higher precision than allowed by the ECMAScript native <code>Number</code> type. So I need to use a custom type (currently <code>BigNumber</code>) to represent those values.</p>
  
  <p>I am looking hungrily at the proposed <code>BigInt</code> type, which when implemented as standard will be an improvement for many applications including the one I'm writing. However that won't help at all with JSON, which knows nothing about <code>BigInt</code> any more than <code>BigNumber</code>.</p>
  
  <p>Whichever custom type I choose, there are many values of this type throughout the application state. So much that it's worth considering a custom hook in the serialisation / deserialisation layer that will handle transforming it to / from JSON.</p>
  
  <p>Presumably the JSON document will have to represent the values as JSON native types (e.g. <code>Object</code> or <code>String</code> instances). How then, when de-serialising the entire complex application state, to reliably recognise and de-serialise those instances among all the others, to the correct value of the correct <code>BigInt</code> or <code>BigNumber</code> type?</p>
  
  <p>How can I serialise that state, such that any <code>BigNumber</code> (or insert some other arbitrary-precision number type) value reliably survives the serialisation / de-serialisation process, to correct values of the correct type?</p>