javascript 中始终效果不够10位补一个0的效果怎么实现

JavaScript013

javascript 中始终效果不够10位补一个0的效果怎么实现,第1张

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

/**

 * @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

 

function formatnumber(value, num){

     var a, b, c, i

     a = value.toString()

     b = a.indexOf(".")

     c = a.length

     if (num == 0) {

         if (b != -1) {

             a = a.substring(0, b)

         }

     } else {//如果没有小数点

         if (b == -1) {

             a = a + "."

             for (i = 1 i <= num i++) {

                 a = a + "0"

             }

         } else {//有小数点,超出位数自动截取,否则补0

             a = a.substring(0, b + num + 1)

             for (i = c i <= b + num i++) {

                 a = a + "0"

             }

         }

     }

     return a

 }

alert(formatnumber(3.1,4))//使用方法,第一个参数是你要转化的小数,第二个是位数

var demo = 5\x0d\x0aalert(demo.toFixed(4))\x0d\x0a\x0d\x0atoFixed(number),格式化数字为保留number位小数的字符串。\x0d\x0a注意,原始值必须是数值,如 var demo = 1demo = demo.toFixed(4)而var demo='1'demo = demo.toFixed(4)是不行的哦。