This article briefly introduces two solutions for JavaScript floating-point overflow. First, let's run a piece of code to see what happens and then let's talk about how to solve this problem.
Two solutions for JavaScript floating point Overflow
Run the following code to find something. This is the JavaScript overflow problem.
- <scripttypescripttype="text/javascript">
- vara=38.8;
- varb=6.8;
- alert(a-b);
- vara=134.22;
- varb=6;
- alert(a*b);
- </script>
-
There are two common solutions to JavaScript overflow:
The first one calls a processing function.
- functionoverflow(a,h,b)
- {if(a.toString().indexOf(".")
- <0&&b.toString().indexOf(".")<0){returneval(a+h+b);
- }varalen=a.toString().split(".");if(alen.length==1){
- alen=0;}else{alenalen=alen[1].length;
- }varblen=b.toString().split(".");if(blen.length==1){
- blen=0;}else{
- blenblen=blen[1].length;}if(blen>alen)alen=blen;blen="1";
- for(;alen>0;alen--){blenblen=blen+"0";
- }switch(h){case"+":return(a*blen+b*blen)/blen;
- break;case"-":return(a*blen-b*blen)/blen;
- break;case"*":return((a*blen)*(b*blen))/(blen*blen);
- break;default:return0;}}
-
The second uses the toFixed method to return a string of numbers in fixed-point notation.
Run the following code.
- <scripttypescripttype="text/javascript">
- vara=38.8;
- varb=6.8;
- alert(overflow(a,"-",b));
- vara=134.22;
- varb=6;
- alert((a*b).toFixed(2));
- </script>