SoFunction
Updated on 2025-02-28

Example analysis of JS long integer precision problem

This article analyzes a JS long integer accuracy problem. Share it for your reference. The specific analysis is as follows:

Problem description:

There is a script function in the background, which can write scripts to call Java code dynamically

Copy the codeThe code is as follows:
importClass(,P360ApiController); 
var roleId = 10214734953631045; 
(roleId, 4);

The script was executed successfully, but the running result was different from the settings. This person did not receive the email

View log recharge award has been sent. roleId=10214734953631044;

This character ID number is 1 less, this...

Problem analysis:

It should be a JS precision issue.

Accuracy

An integer (without decimal or exponential counting) has a maximum of 15 digits.
The maximum number of digits of a decimal is 17, but floating point operations are not always 100% accurate:

Modify the script

Copy the codeThe code is as follows:
var roleId = 10214734953631045; 
var output = roleId;

Output:
1.0214734953631044E16;

This is not the fault of JavaScript, nor is it the fault of Java. The conversion to Long is indeed roleId=10214734953631044;

Can that be done?
The javascript console inputs strings, and then calls java or converts?

Solution:

Write a general conversion method. Objective to pass the role ID into JavaScriptEngine in string.

Copy the codeThe code is as follows:
importClass(); 
importClass(,P360ApiController);

Declare as a string

Copy the codeThe code is as follows:
var roleId = "10214734953631045";

In this way, what JavaScriptEngine gets is a string. In fact, the job is Java to process it.
Copy the codeThe code is as follows:
((roleId), 4);

The execution is successful, just use it first~

I hope this article will be helpful to everyone's JavaScript programming.