Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How js Converts Pure Numeric Strings into Long Types
How js Converts Pure Numeric Strings into Long Types
The accuracy of JavaScript decimal arithmetic will be lost, which will bring a lot of inconvenience to the project. Please have a look at the following script first:

javascript,javascript

& ltscript type = " text/JavaScript " language = " JavaScript " & gt;

alert( 1/3); //popup: 0.3300000000005

Early warning (0.09999999+0.0000001); //popup: 0.09999

alert(-0.09999999-0.000000 1); //popup:-0.0000.00000005

alert(0.0 12345 * 0.0000 1); //popup: 1.9999e-8。

alert(0.00000 1/0.000 1); //Pop-up window: 0.56860.56860888886

& lt/script & gt;

According to the normal calculation, except the first line (because it can't be divided by itself), everything else should get accurate results, but from the pop-up results, we find that it is not the correct result we want. In order to solve the problem of inaccurate floating-point number operation, we upgrade the number to integer (10 to the x power) before the operation, and then downgrade it (0. 1 to the x power) after the operation. Now collect and paste it here for later use.

javascript,javascript

//addition

number . prototype . add = function(arg){

var r 1,r2,m;

Please try {r 1=this.toString (). Split (".") [1]. length} catch (e) {r1= 0}

Please try {r2=arg.toString (). Split (".") [1]. Length} Capture (e){r2=0}

m=Math.pow( 10,Math.max(r 1,r2))

return (this*m+arg*m)/m

}

//subtraction

number . prototype . sub = function(arg){

Return this.add (-arg);

}

//multiplication

Number.prototype.mul = function (arg)

{

var m=0,s 1=this.toString(),S2 = arg . tostring();

Please try {m+= s1.split (".") [1]. length} catch (e) {}

Try {m+= s2.split (".") [1]. length} catch (e) {}

Returns the number (s 1.replace (".","")) * number (s2.replace (".","")) /Math.pow( 10, m).

}

//division

number . prototype . div = function(arg){

var t 1=0,t2=0,r 1,R2;

Please try {t 1=this.toString (). Split (".") [1].length}catch(e){}

Please try {t2=arg.toString (). Split (".") [1].length}catch(e){}

Use (mathematics) {

r 1=Number(this.toString()。 Replace (".",""))

r2=Number(arg.toString()。 Replace (".",""))

return(r 1/R2)* pow( 10,T2-t 1);

}

}

test

javascript,javascript

& ltscript type = " text/JavaScript " language = " JavaScript " & gt;

Alarm (number: 0.09999999). Plus (0.00000001)); //popup: 0. 1

//Note that if it is a negative number, it must be converted by numbers first, otherwise the result will be incorrect.

Alarm (number (-0.09999999). sub(0.0000000 1)); //popup: -0. 1

Alarm (number (0.0 12345). mul(0.00000 1)); //popup: 1.2345e-8

Alarm (number (0.00000 1). div(0.000 1)); //popup: 0.0 1

& lt/script & gt;