반응형
문자열의 제로 패드 숫자
단일 숫자 (1 ~ 9)를 (01 ~ 09)로 캐스팅해야합니다. 나는 길을 생각할 수 있지만 그 크고 추악하고 성가시다. 간결한 방법이 있어야합니다. 어떤 제안
우선, 귀하의 설명이 잘못되었습니다. Double
부동 소수점 데이터 유형입니다. 아마도 문자열에서 선행 0으로 숫자를 채우려 고합니다. 다음 코드가이를 수행합니다.
$s = sprintf('%02d', $digit);
자세한 내용은의 설명서를 참조하십시오 sprintf
.
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
str_pad를 사용하는 솔루션 :
str_pad($digit,2,'0',STR_PAD_LEFT);
PHP 5.3 벤치 마크
결과 str_pad : 0.286863088608
결과 스프린트 : 0.234171152115
암호:
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
str_pad(9,2,'0',STR_PAD_LEFT);
str_pad(15,2,'0',STR_PAD_LEFT);
str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
sprintf("%02d", 9);
sprintf("%02d", 15);
sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";
참고 URL : https://stackoverflow.com/questions/324358/zero-pad-digits-in-string
반응형
'developer tip' 카테고리의 다른 글
Visual Studio에서 마지막 커서 위치로 다시 이동하는 방법은 무엇입니까? (0) | 2020.07.24 |
---|---|
Gulp 오류 : 'jshint / src / cli'모듈을 찾을 수 없습니다 (0) | 2020.07.24 |
UIRefreshControl-UITableViewController가 UINavigationController 내에있을 때 beginRefreshing이 작동하지 않습니다. (0) | 2020.07.24 |
Visual Studio Code : 형식이 들여 쓰기 설정을 사용하지 않습니다 (0) | 2020.07.24 |
Java에서 구분 기호가없는 문자열로 긴 정수를 어떻게 포맷합니까? (0) | 2020.07.24 |