Get precision from a number - Node.js Number

Node.js examples for Number:Algorithm

Description

Get precision from a number

Demo Code

/**/*from www  .ja v a 2 s  . c  om*/
 * Get precision
 * @param {number} val
 */
number.getPrecision = function (val) {
    if (isNaN(val)) {
        return 0;
    }
    // It is much faster than methods converting number to string as follows
    //      var tmp = val.toString();
    //      return tmp.length - 1 - tmp.indexOf('.');
    // especially when precision is low
    var e = 1;
    var count = 0;
    while (Math.round(val * e) / e !== val) {
        e *= 10;
        count++;
    }
    return count;
};

Related Tutorials