Browse Source

debug roundTo

zhongzewei 7 years ago
parent
commit
0df5f7c653
1 changed files with 22 additions and 2 deletions
  1. 22 2
      public/web/scMathUtil.js

+ 22 - 2
public/web/scMathUtil.js

@@ -2,6 +2,9 @@
  * Created by jimiz on 2017/3/28.
  * 经验证:10000次四舍五入,用num.toFixed为15毫秒,用roundTo为47毫秒,速度低一些,但可以接受
  * 另:经手工验证,用num.toString(2)将十进制浮点数转换为二进制浮点数时,最后一位有错误的情况出现,例子(10.0311)
+ *
+ * zhangyin 2018-02-28
+ * 采用重复一次四舍五入解决浮点精度误差后,10000次roundTo的时间为94毫秒。
  */
 
 let scMathUtil = {
@@ -152,13 +155,30 @@ let scMathUtil = {
         };
         return result;
     },
-    roundTo: function(num, digit){
+    reRoundTo: function(num, digit){
         let me = this;
         return me.innerRoundTo(me.binToFloat(me.incMantissa(me.floatToBin(num))), digit);
     },
+    // zhangyin 2018-02-28
+    // 经过运算后的浮点数,误差可能更大,加尾数也不能消除。目前采用笨办法,将有效位数加一位再四舍五入一次,以消除浮点误差。
+    // 此办法效率较低,没有别的更好办法时暂时用着
+    roundTo: function(num, digit){
+        let me = this;
+        return me.reRoundTo(me.reRoundTo(num, digit - 1), digit);
+    },
     isNumber : function (obj) {
         return obj === +obj;
     },
+    roundForObj:function(obj,decimal){
+        let me = this;
+        let value;
+        if(me.isNumber(obj)){
+            value = me.roundTo(obj,-decimal)
+        }else {
+            value = me.roundTo(Number(obj),-decimal);
+        }
+        return value
+    },
     roundToString:function(obj,decimal){
         let me = this;
         let value;
@@ -173,7 +193,7 @@ let scMathUtil = {
 
 Number.prototype.toDecimal = function (ADigit) {
     //return parseFloat(this.toFixed(ADigit));
-    digit = (ADigit && typeof(ADigit) === 'number' && Number.isInteger(ADigit) && ADigit >= 0) ? -ADigit : -2;
+    digit = ((ADigit!=null||ADigit!=undefined) && typeof(ADigit) === 'number' && Number.isInteger(ADigit) && ADigit >= 0) ? -ADigit : -2;
     // var s = scMathUtil.roundTo(this, digit);
     // console.log('Number: ' + this + '   Digit: ' + digit + '    Result: ' + s);
     // return parseFloat(s);