Categories
JavaScript Answers

How to reduce numbers’ significance when stringifying values with JavaScript JSON.stringify?

Spread the love

Sometimes, we want to reduce numbers’ significance when stringifying values with JavaScript JSON.stringify.

In this article, we’ll look at how to reduce numbers’ significance when stringifying values with JavaScript JSON.stringify.

How to reduce numbers’ significance when stringifying values with JavaScript JSON.stringify?

To reduce numbers’ significance when stringifying values with JavaScript JSON.stringify, we can call JSON.stringify with a function that rounds numbers to the number of decimal places we want.

For instance, we write:

const a = [0.123456789123456789]
const strA = JSON.stringify(a, (key, val) => {
  return typeof val === 'number' ? Number(val.toFixed(3)) : val;
})
console.log(strA)

to call JSON.stringify with a and a callback that checks if the val value being stringified if a number.

If it is, we call val.toFixed with 3 to round val to 3 decimal places.

Otherwise, we return val as is.

Therefore, strA is '[0.123]'.

Conclusion

To reduce numbers’ significance when stringifying values with JavaScript JSON.stringify, we can call JSON.stringify with a function that rounds numbers to the number of decimal places we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *