简体   繁体   中英

Override console.log to format numbers

I often need to log numbers to the console during javascript debugging but I don't need all the decimal places.

console.log("PI is", Math.PI); // PI is 3.141592653589793

How can I override console.log to always format numbers with 2 decimal places?

NB: Overriding Number.prototype.toString() does not achieve this.

Overriding inbuilt stuff is a very very bad idea. May write your own small function as a shortcut:

 const log = (...args)=> console.log(...args.map(el => typeof el === "number"? Number(el.toFixed(2)) : el )); log("Math.PI is ", Math.PI); 

You could take a monkey patch for console.log , which is not advisable, usually.

 void function () { var log = console.log; console.log = function () { log.apply(log, Array.prototype.map.call(arguments, function (a) { return typeof a === 'number' ? +a.toFixed(2) : a; })); }; }(); console.log("PI is", Math.PI); // PI is 3.14 console.log("A third is", 1/3); // A third is 0.33 

Make a quick shortcut function which is easy to type and formats numbers:

    const dp = function() {
        let args = [];
        for (let a in arguments) args.push(typeof arguments[a] == "number"?arguments[a].toFixed(2):arguments[a])
        console.log.apply(console, args);
    }

Gives you:

dp("PI is", Math.PI); // PI is 3.14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM