格式编号允许三位小数而不是两位数

时间:2017-10-26 22:38:40

标签: javascript

我创建的格式允许小数点后两位数,例如99.9955.55等。我想允许99.999而不是两位数。不确定问题出在哪里。

function formatNumber (nStr) {
    nStr = String(nStr)
    nStr = nStr.replace(/\,/g, '')
    nStr = trimNumber(nStr)

    if ($.isNumeric(nStr)) {
        nStr = String(parseFloat(nStr).toFixed(2))
        nStr += ''
        x = nStr.split('.')
        x1 = x[0]
        if (x.length > 1) {
            if (x[1].length > 2) {
                var thirddigit = x[1].substr(2, 1)
                var addone = false
                if (Number(thirddigit) >= 5) {
                    addone = true
                }

                x[1] = x[1].substr(0, 2)
                if (addone) {
                    var y = Number(x[1]) + 1
                    x[1] = y
                }
            }
        }
        x2 = x.length > 1 ? '.' + x[1] : ''
        var rgx = /(\d+)(\d{3})/
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2')
        }

        if (x.length > 1) {
            if (x[1].length == 1) {
                x2 = '.' + x[1] + '0'
            }
            if (x[1].length == 0) {
                x2 = '.00'
            }
        } else {
            if (x1 != '') {
                x2 = '.00'
            }
        }

        if (getLeft(x1 + x2, 1) == '.') {
            return '0' + x1 + x2
        } else {
            return x1 + x2
        }
    } else {
        return ''
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!我发布它,以防任何人有相同的情况,需要它。

function Format3DigitDecimal(e, thisobj, min, max) {
        var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode))

        var inStr = $(thisobj).val()




        if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
        {
            if ((inStr.length >= max.toString().length) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
            {
                ret = false
            }
        }

        if (ret && (inStr != '' && (keyCode >= 48 && keyCode <= 57)))
        {
            if ((inStr.length == 3) && ((thisobj.selectionStart - thisobj.selectionEnd) == 0))
            {
                ret = false
            }
        }

        return ret
    }