Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish between Integer and Double in V8

Tags:

c++

c++11

v8

In my implementation I provide a function to JavaScript that accepts a parameter.

v8::Handle<v8::Value> TableGetValueIdForValue(const v8::Arguments& args) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::HandleScope handle_scope(isolate);

  auto val = args[1];

  if (val->IsNumber()) {

    auto num = val->ToNumber();
    // How to check if Int or Double    

  } else { 
     // val == string 
  }
}

Now this parameter can have basically any type. As I support Int, Float and String I want to efficiently check for these types. Using IsNumber() and IsStringObject() I can make sure that the objects are numberish or a string.

But now I need to differentiate between an integer value and a float. What is the best way to perform this test? Is there a way to call / use the typeof function exposed to JS?

like image 762
grundprinzip Avatar asked Jan 14 '23 04:01

grundprinzip


2 Answers

Quick Answer

v8::Value::NumberValue() will will return the value of the javascript Number without loss of precision.

Explanation

It is true that the set of numbers representable by int64_t and double is different. And so is natural to be concerned about what happens if the value is actually int64_t because v8::Value defines both

V8EXPORT int64_t v8::Value::IntegerValue() const;
V8EXPORT double v8::Value::NumberValue() const;

What is a v8::Number?

Consider v8::Number doc

Detailed Description

A JavaScript number value (ECMA-262, 4.3.20)

IntegerValue does return an int64_t, but there will be no more precision available, because the value is stored internally as a double-precision 64-bit binary format IEEE 754 value.

Testing in a browser

Checking if javascript can represent a value that a double can't but an int64_t can.

2^63 - 1 is equal to 9223372036854775807

Try typing the following in a javascript console; this value is parsed but the extra precision is thrown away because double can't represent it.

>9223372036854775807

the result

9223372036854776000
like image 198
waTeim Avatar answered Jan 25 '23 20:01

waTeim


Try IsInt32 or IsUint32() to check the number is integer or not.

https://github.com/v8/v8/blob/master/include/v8.h#L1313

like image 37
mattn Avatar answered Jan 25 '23 19:01

mattn