在js中如何做数字字符串补0

JavaScript023

在js中如何做数字字符串补0,第1张

// 改成这样<input type="text" name="username" value='<%=UserLoginId %>' id="username" required="required" placeholder="用户名" onblur="var v=this.valuewhile(v.length<6){v='0'+v}this.value=v" />

下面是我写的一个方法, 应该可以满足你的要求

/**

 * @param num: 需要固定位数的数字或字符串

 * @param totalBit: 保证返回字符串的长度, 默认为10

 * @param isFront: 当num位数不足时, 新填充的字符串是否位于num前面, 默认为true

 * @param fixedChar: 当num位数不足时, 重复填充此字符, 默认为'0'

 * @param alwaysCut: 是否始终保证返回值长度为totalBit, 此值为true时, 如果给定num的长东超过参数中totalBit的大小时, 也会截取totalBit长度的字符串, 默认为false

 * **/

function toFixedBit(num, totalBit, isFront, fixedChar, alwaysCut) {

    if (totalBit === void 0) { totalBit = 10 }

    if (isFront === void 0) { isFront = true }

    if (fixedChar === void 0) { fixedChar = "0" }

    if (alwaysCut === void 0) { alwaysCut = false }

    var nn = num.toString()

    if (!alwaysCut && nn.length >= totalBit) {

        return nn

    }

    var rtn = ""

    for (var i = 0 i < totalBit i++) {

        rtn += fixedChar

    }

    if (isFront) {

        rtn += nn

        rtn = rtn.substr(rtn.length - totalBit)

    }

    else {

        rtn = nn + rtn

        rtn = rtn.substr(0, totalBit)

    }

    return rtn

}

使用方法

console.log(toFixedBit(100)) //输出: 0000000100

console.log(toFixedBit(100, 10, false))//输出: 1000000000

console.log(toFixedBit(100, 10, true, "$", false))//输出: $$$$$$$100

console.log(toFixedBit("aasadfsa4512122", 10, true, "$", true))//输出: fsa4512122

console.log(toFixedBit("aasadfsa4512122", 10, false, "$", true))//输出: aasadfsa45

console.log(toFixedBit("aasadfsa4512122", 10, false, "$", false))//输出: aasadfsa4512122

1)在input失去焦点的func里面操作,

2)检查文本的长度:

if 文本长度离目标长度相差n的话

then input的文本 = n*0 + 原文本

即可。