Skip to main content

Use case

The REST (JSON) API returns numeric measure and dimension values as strings. However, we’d like to receive them as JavaScript Number type. In the recipe below, we explore a way to have numeric values automatically converted to Number. This is a potentially unsafe operation, so we also explore when it’s safe to do so.

Data modeling

Let’s assume we have the following cube with a numeric dimension and a numeric measure:

Query via the REST (JSON) API

Let’s send the following query via the REST (JSON) API:
Unsurprisingly, we’ll get the following result set in respose:
You can see that the REST (JSON) API returns numeric measure and dimension values as strings. While it might counter-intuitive, this is actually by design. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. They can only safely represent integers between –9007199254740991 and 9007199254740991, also known as Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER. It’s also true with regards to JSON numbers since they are handled by the JavaScript runtime. That is why the REST (JSON) API returns numeric measure and dimension values as strings by default. Depending on the nature of your data and domain, you can decide that numbers are “safe integers” and parse them as instances of the Number type; alternatively, you can parse them as instances of the BigInt type. JavaScript SDK provides convenient facilities for the case when all numbers are considered “safe integers”. See how to use them below.

Query via the JavaScript SDK

Let’s use JavaScript SDK to send the same query and print the result set to the browser console:
In the first case, numeric measure and dimension values will be rendered as strings:
In the second case, when the castNumerics flag is set to true, numeric values are automatically cast to number. As the result, some numbers consequently loose precision:
It is advised to use castNumerics only in cases when you’re sure that you work with “safe integers”.