Clearscript: Reliably give doubles for numeric 0.0

Created on 21 Jan 2020  路  4Comments  路  Source: microsoft/ClearScript

Consider this code

using (var host = new V8ScriptEngine())
{
    host.Script.X = 1.0;
    Console.WriteLine(host.Script.X.GetType().FullName);

    dynamic dynamic = new { X = 1.0 };
    Console.WriteLine(dynamic.X.GetType().FullName);
}

This emits this

System.Int32
System.Double

What this means is that when we put a double number into ClearScript, we might expect that number to be treated as a double. After all, it went in as a double, could be 1.5 in our business case, and JavaScript's numbers aren't true ints.

Because of this we have to do some extra handling on the way back, casting back to a double.

Could we somehow switch this behaviour off, so that numbers are always treated as doubles?

question

All 4 comments

Hi @JohnLudlow,

Could we somehow switch this behaviour off, so that numbers are always treated as doubles?

ClearScript doesn't offer such an option because enabling it would create a new, more serious problem.

Currently JavaScript numbers are imported as integers (when possible) in order to facilitate a very common scenario - passing integer arguments to host methods.

In .NET, floating-point values aren't implicitly convertible to integers (see here). Therefore, without ClearScript's automatic conversion, script code would have to cast each integer argument manually. And since JavaScript has no native numeric casting facility, this could only be accomplished by wrapping the argument via something like HostFunctions.toInt32, which would add temendous overhead, not to mention inconvenience, to such invocations.

We figured that host-side casting, via either the cast operator or Convert, would be easier and incur less performance impact.

Cheers!

Yeah, that's what I figured.

Please reopen this issue if you have further thoughts on this topic. Thanks!

Will do. We're investigating alternatives, but will probably end up trying to cast to double.

What complicates this slightly is that the code which handles this has no idea what it's actually dealing with, and some of that code is C++ talking to .NET via C++/CLI.

Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bhaeussermann picture bhaeussermann  路  6Comments

JohnLudlow picture JohnLudlow  路  4Comments

fasihrana picture fasihrana  路  8Comments

drearyrainDeng picture drearyrainDeng  路  3Comments

roblarky picture roblarky  路  3Comments