Get precision of a number - Node.js Number

Node.js examples for Number:Parse

Description

Get precision of a number

Demo Code


/**/*w  w  w .j  a v  a 2  s . co m*/
 * 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