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
版权声明:本文为博主原创文章,转载请附上博文链接!