Home > Web Front-end > JS Tutorial > body text

Example analysis of JS long integer precision problem_javascript skills

WBOY
Release: 2016-05-16 16:20:22
Original
1263 people have browsed it

This article analyzes a JS long integer precision problem in an example. Share it with everyone for your reference. The specific analysis is as follows:

Problem description:

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

Copy code The code is as follows:
importClass(com.ztgame.center.controller.api,P360ApiController);
var roleId = 10214734953631045;
p360ApiController.notice(roleId, 4);

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

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

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

Problem analysis:

It should be a JS precision issue,

Accuracy

Integers (without decimal point or exponent notation) can be up to 15 digits.
The maximum number of decimal places is 17, but floating point arithmetic is not always 100% accurate:

Modify script

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

Output:
1.0214734953631044E16;

This is not JavaScript’s fault, nor is it Java’s fault. The above conversion to Long is indeed roleId=10214734953631044;

Is that possible?
The javascript console inputs are all strings, and then calls Integer.valueOf or Long.valueOf conversion in java?

Solution:

Write a general conversion method to pass the character ID to JavaScriptEngine as a string

Copy code The code is as follows:
importClass(com.ztgame.common.util.StringKit);
importClass(com.ztgame.center.controller.api,P360ApiController);

Declared as string

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

In this way, what JavaScriptEngine gets is a string. In fact, the work is handled by Java
Copy code The code is as follows:
p360ApiController.notice(StringKit.parseLong(roleId), 4);

The execution is successful, just use it like this~

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template