nvpt
4/24/2018 - 8:23 AM

get decimal

Получение значения дробной части числа. С определением число/не число. С возможностью использования parseFloat

/**
 * Get decimal data ov value with checking, is it number
 * @param el - number value
 * @param useParseFloat - marker. Use or not parseFloat. Default - not
 * @returns {*}
 */
function getDecimal(el, useParseFloat = false) {
    function isNumber(x) {
        return useParseFloat ? !isNaN(parseFloat(x)) && isFinite(parseFloat(x)) : !isNaN(parseFloat(x)) && isFinite(x);
    }

    if (isNumber(el)) {
        let val = parseFloat(el);
        let index = /(.*)\.(.*)/g.exec(val + '')
            ? /(.*)\.(.*)/g.exec(val + '')[2] ? /(.*)\.(.*)/g.exec(val + '')[2].length
                : null
            : null;
        if (index) {
            return Math.round((val % 1) * Math.pow(10, index)) / Math.pow(10, index);
        } else {
            console.info('The decimal is miss');
            return null;
        }
    }
    console.info('The value is not number');
    return null;
}

console.log(getDecimal('16.44px', true));