JavaScript字符串或者数字按照规定位数输出,位数不够补0或者空格,整数和小数两种方法

 1.整数方法补0或者任意字符
 * @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


    2.小数点后补0

     项目需要,使用经纬度,但是经纬度经常变化,所以要自动补0,在http://www.jb51.net/article/76612.htm中看到一段代码,适用于小数点1到2位,多了就很麻烦,后来查到JavaScript toFixed()方法,Qt代码片段如下。
    function add(value){
       return value.toFixed(7);
    }
  Rectangle{
      id:leftbottomarea;
      width:parent.width/2;
      height:parent.height/12;
      color: "black";
      anchors.left: parent.left;
      anchors.bottom: parent.bottom;
      anchors.leftMargin: 2;
      anchors.bottomMargin: 2;
      opacity: 0.7;
//    visible:activeVehicle ? true : false;
      Text {
                
      text:add(8.55456);
          anchors.centerIn:  leftbottomarea;
          color: "white";
          font.pixelSize: parent.width/18;
          font.family: "Times New Roman";
        //  opacity: 0.9;
      }
  }
--------------------- 
作者:aadx 
来源:CSDN 
原文:https://blog.csdn.net/qq_38159549/article/details/80265132 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值