美文网首页
js浮点运算0.1+0.2=0.3和日期格式化

js浮点运算0.1+0.2=0.3和日期格式化

作者: 左撇子小晨 | 来源:发表于2020-08-06 09:53 被阅读0次
    //调用方法:Number.add(0.1, 0.2)
    //Date.fmt(1596509653796 , "YYYY-MM-DD hh:mm:ss")
    
    Object.prototype.addMethod = function (name, fn) {
        var old = this[name];
        this[name] = function () {
            var fncLen = fn.length,
                argLen = arguments.length;
            if (fncLen === argLen) {
                return fn.apply(this, arguments);
            } else if (typeof old === "function") {
                return old.apply(this, arguments);
            } else {
                throw new Error("no method with " + argLen + " param(s) defined!");
            }
        }
    }
    
    /*
    * 核心方法,实现加减乘除运算,确保不丢失精度
    * 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
    *
    * @param a {number} 运算数1
    * @param b {number} 运算数2
    * @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
    *
    */
    
    var __number__ = {
        operation: function (a, b, op) {
            var o1 = __number__.toInteger(a || 0);
            var o2 = __number__.toInteger(b || 0);
            var n1 = o1.num;
            var n2 = o2.num;
            var t1 = o1.times;
            var t2 = o2.times;
            var max = t1 > t2 ? t1 : t2;
            var result = null;
    
            switch (op) {
                case 'add':
                    if (t1 === t2) { // 两个小数位数相同
                        result = n1 + n2
                    } else if (t1 > t2) { // o1 小数位 大于 o2
                        result = n1 + n2 * (t1 / t2)
                    } else { // o1 小数位 小于 o2
                        result = n1 * (t2 / t1) + n2
                    }
                    return result / max;
    
                case 'subtract':
                    if (t1 === t2) {
                        result = n1 - n2
                    } else if (t1 > t2) {
                        result = n1 - n2 * (t1 / t2)
                    } else {
                        result = n1 * (t2 / t1) - n2
                    }
                    return result / max;
    
                case 'multiply':
                    result = (n1 * n2) / (t1 * t2);
                    return result;
    
                case 'divide':
                    result = (n1 / n2) * (t2 / t1);
                    return result
            }
        },
    
        isInteger: function (obj) {
            return Math.floor(obj) === obj
        },
    
        /*
        * 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
        * @param floatNum {number} 小数
        * @return {object}
        *  {times:100, num: 314}
        */
    
        toInteger: function (floatNum) {
            var ret = {
                times: 1,
                num: 0
            };
    
            if (__number__.isInteger(floatNum)) {
                ret.num = floatNum;
                return ret
            }
    
            var strfi = floatNum + '';
            var dotPos = strfi.indexOf('.');
            var len = strfi.substr(dotPos + 1).length;
            var times = Math.pow(10, len);
            var intNum = parseInt(floatNum * times + 0.5, 10);
            ret.times = times;
            ret.num = intNum;
            return ret
        },
    
        add: function (a, b) {
            return __number__.operation(a, b, 'add')
        },
    
        subtract: function (a, b) {
            return __number__.operation(a, b, 'subtract')
        },
    
        multiply: function (a, b) {
            return __number__.operation(a, b, 'multiply')
        },
    
        divide: function (a, b) {
            return __number__.operation(a, b, 'divide')
        }
    
    }
    
    Number.addMethod('add', __number__.add) // Number.add(0.1, 0.2)
    Number.addMethod('subtract', __number__.subtract)
    Number.addMethod('multiply', __number__.multiply)
    Number.addMethod('divide', __number__.divide)
    
    var __date__ = {
        /**
        *  fmt = "YYYY-MM-DD hh:mm:ss" => 2016-04-01 10:41:08
        *  fmt = "YY-MM-DD hh:mm:ss" => 16-04-01 10:41:08
        *  fmt = "Y-M-D hh:mm:ss" => 16-4-1 10:41:08
        *  fmt = "MM/DD<br>hh:mm" => 01/12<br>12:05
        **/
    
        fmt: function (timestamp, fmt) {
            if (typeof timestamp === 'string')
                timestamp = parseInt(timestamp, 10)
                
            const t = new Date(timestamp)
            var o = {
                "Y+": t.getFullYear(),
                "M+": t.getMonth() + 1,
                "D+": t.getDate(),
                "h+": t.getHours(),
                "m+": t.getMinutes(),
                "s+": t.getSeconds()
            };
    
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    if (k == "Y+") fmt = fmt.replace(RegExp.$1, ("" + o[k]).substr(4 - RegExp.$1.length));
                    else fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
    
            return fmt;
        },
    
        /**
        * 星期一:Monday(Mon.)
        * 星期二:Tuesday(Tues.)
        * 星期三:Wednesday(Wed.)
        * 星期四:Thursday(Thur./Thurs.)
        * 星期五:Friday(Fri.)
        * 星期六:Saturday(Sat.)
        * 星期日:Sunday(Sun.)
        **/
    
        get_week: function (timestamp, fmt) {
            if (typeof timestamp === 'string')
                timestamp = parseInt(timestamp, 10)
            const t = new Date(timestamp).getDay()
    
            if (fmt == 'zh') {
                fmt = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
            } else if (fmt == 'en') {
                fmt = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
            } else if (fmt == 'zh-abbr') {
                fmt = ["日", "一", "二", "三", "四", "五", "六"]
            } else if (fmt == 'en-abbr') {
                fmt = ["Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"]
            } else if (!Array.isArray(fmt)) {
                return t
            }
    
            return fmt[t];
        }
    }
    
    Date.addMethod('fmt', __date__.fmt)
    Date.addMethod('get_week', __date__.get_week)
    

    相关文章

      网友评论

          本文标题:js浮点运算0.1+0.2=0.3和日期格式化

          本文链接:https://www.haomeiwen.com/subject/kvrwrktx.html