DEV Community

Cover image for JSON and Number Formats
Eric McCormick
Eric McCormick

Posted on • Originally published at edm00se.io on

JSON and Number Formats

I know it's been a while, figured I'd pop up write a quick blog.

a kraken lifting a sailing ship above water, cracking it in half, and dumping the people into the sea

Numbers came up as a topic today, you know, thse primitive entities in JavaScript. Yeah, I was surprised as well.

The Problem

Whether this is truly a problem is debatable. Working in an almost exclusively node and TS/JS context these days, my code lives and dies based on what my runtime supports. Usually this is defined by node and its implementation of the v8 engine. Today this means specifically its implementation of JSON and its parse and stringify methods. I thought knew about everything there was to know about JSON, short of JSON 5 which sadly looks like it won't be supported by node anytime soon, but while unsurprised, I learned something today. The short version is that numeric values in JSON strings need to be valid floats or ints, this shouldn't be a surprise to anyone experienced with JavaScript. Where the rubber meets the road is that in the process of JSON.stringifying or JSON.parseing, any trailing .0 on a numeric value will be stripped. Of course it still is of the correlating value, and if decimal places are needed, you could pass the value as a string, but that's silly. What's also silly is the inevitable kickback one could get when matching an existing system's output when migrating to a new one.

Why Is This a "Problem"?

As far as I can tell, the previously generated output was coming from a C based runtime that was generating the output with complete abandon for the ultimate JSON output itself. It succeeded in creating a numeric value that was parsable as either a float or int, making it technically correct, but mildly unhelpful and an annoyance for me, here in the future. JavaScript, JSON parse, and JSON stringify will each strip the .0 specificity as its unnecessary for it as a numeric value, either as an int or float; it's just not needed and any need to display the value differently would likely require using .toFixed, because that's a function of display, not numeric value. Futurama GIF showing a lawyer character stating

An Example

Summary

When in doubt, check what you know. We'll see whether I need to do some custom string processing or not; preferably the latter. Still, I've gone down the custom JSON serialization path before, but that was on another platform with different tooling and reasons. Until next time.

JSON and Number Formats was originally published at edm00se.io on 06-Oct-2023.

Top comments (0)