How to check a napi_value of type napi_number is an integer or decimal by using node.js N-API function,

1.2k Views Asked by At

How to check a given napi_value of type napi_number is an integer or decimal (a number with fractional value) by using node.js native N-API function . Look like there is no isInt() or isDouble() equivalent function in N-API (we don’t want to use V8 function call either). Let us consider a scenario where we are calling a native addon function f1() from JavaScript by passing a JavaScript object as argument as shown in the snippet.

let obj = { n1: 123, n2: 123.45 };
myaddon.f1( obj );

The native function f1() want to extract value associated with the keys n1 and n2 by calling the best fit value extraction N-API function. For example to extract value of n1 it may be best to use one of napi_get_value_int* and similarly for the n2 the double is a better choice.

napi_get_value_double
napi_get_value_int32
napi_get_value_uint32
napi_get_value_int64

Unfortunately I could not find any N-API function to verify the derivative of napi_number property. Have you come across similar situation, if so how did you solve this problem?

https://nodejs.org/api/n-api.html

1

There are 1 best solutions below

0
On

A request has been opened with node-addon-api team regarding this feature and they provided an answer that sound logical. I thought of sharing the answer with this community that may help similar queries others may have. Here is the answer from node-addon-api team

While handling numbers with JavaScript, it is important to know that all numbers in JavaScript are double-precision 64 bit IEEE 754 values (despite some engines like v8 might have additional represents on small integers, there is no such definition in ECMA spec and no way to determine these types of number in JavaScript).

napi_get_value_{double,int32,uint32,int64} just convert these value to its desired one. There might be a precision loss in the conversion. If a determined number is required in the case, use BigInt instead.