Home >Web Front-end >JS Tutorial >javascript zero padding function collection_javascript skills

javascript zero padding function collection_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:54:581531browse

When outputting an integer, if you need to add zeros at the front or back to a certain length, you can use the following function.

Copy code The code is as follows:

function padLeft(str,lenght){
if (str.length >= lenght)
return str;
else
return padLeft("0" str,lenght);
}
function padRight(str,lenght){
if(str.length >= lenght)
return str;
else
return padRight(str "0",lenght);
}

before number Automatic zero padding function
function
function xx(a,b,c)
{
....
}

parameters
xx(98,102, 4)

Result

0098 0099 0100 0101 0102
-------------------------- --------------------------
I wonder if everyone understands?

Give a starting value (any positive integer less than B), an end value (any positive integer greater than A), and a limit length value (any positive integer), the function can be automatically generated A number, automatically padded with zeros in front
The following is the implementation code

[Ctrl A Select All Note: If you need to introduce external Js, you need to refresh to execute
]

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]

Enter 1, Then it becomes 001, 2 is 002, 10 is 010, and so onCopy code
The code is as follows:


/**Format the number as a fixed-length string, with 0s added in front
* Parameters:
* Source The string to be formatted
* Length The length of the string to be obtained
*/
function FormatNum(Source,Length){
var strTemp="";
for(i=1;i<=Length-Source.length ;i ){
strTemp ="0";
}
return strTemp Source;
} <script> function addZero(a,b,c) { while(a<b) { t=a+""; while(t.length<c)t="0"+t; a++; document.write(t+"<br>"); } } addZero(1,10,5); </script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn