æ°å¤ã®å é ã«0ã追å ãã¦æ¡ãããããé¢æ°ããã°ã£ã¦ããã®ã§ä¿®æ£ã
この間作成した数値の先頭に0を追加して桁をあわせる関数ããã°ã£ã¦ããã®ã§ä¿®æ£ã「Math.log(0)」って-Infinityを返すã®ãã»ã»ã»orzããã¨è² æ°ã®å ´åãNaNã«ãªãã®ãã
Math.log( 0 ) // -Infinity Math.log( -1 ) // NaN Math.log( -100 ) // NaN
ã¨ãããã¨ã§ãé¢æ°ã«æ¡ä»¶å¤å®ã追å ã
/** * å¿ è¦ãªæ¡æ°ã¾ã§0ãåããã * @param number æ¡æ° * @param size æ¡æ° */ function fillZero( number, size ) { if ( number < 0 ) throw "illegal argument."; var s = number != 0 ? Math.log( number ) * Math.LOG10E : 0; for( i=1,n=size-s,str="";i<n;i++ ) str += "0"; return str+number; }
ãµã³ãã«ã
var out = document.getElementById("out"); out.innerHTML += "3, 1 : " + fillZero( 3, 1 ) + "<br/>"; out.innerHTML += "3, 2 : " + fillZero( 3, 2 ) + "<br/>"; out.innerHTML += "3, 3 : " + fillZero( 3, 3 ) + "<br/>"; out.innerHTML += "23, 3 : " + fillZero( 23, 3 ) + "<br/>"; out.innerHTML += "123, 3 : " + fillZero( 123, 3 ) + "<br/>"; out.innerHTML += "1234, 3 : " + fillZero( 1234, 3 ) + "<br/>"; out.innerHTML += "3.2, 2 : " + fillZero( 3.2, 2 ) + "<br/>"; out.innerHTML += "0, 1 : " + fillZero( 0, 1 ) + "<br/>"; out.innerHTML += "0, 2 : " + fillZero( 0, 2 ) + "<br/>"; out.innerHTML += "0, 3 : " + fillZero( 0, 3 ) + "<br/>"; try { fillZero( -3, 2 ); } catch ( ex ) { out.innerHTML += "-3, 2 : illegal argument.<br/>"; } try { fillZero( -10, 2 ); } catch ( ex ) { out.innerHTML += "-10, 2 : illegal argument.<br/>"; }