2013-08-16 12 views

回答

0

事實證明,它可以用這個功能來實現:

//format a number into specified number of decimals 
function formatDecimals(num, digits) { 
    //if no decimal places needed, we're done 
    if (digits <= 0) { 
     return Math.round(num); 
    } 
    //round the number to specified decimals 
    var tenToPower = Math.pow(10, digits); 
    var cropped = String(Math.round(num * tenToPower)/tenToPower); 
    //add decimal point if missing 
    if (cropped.indexOf(".") == -1) { 
     cropped += ".0"; 
    } 
    //finally, force correct number of zeroes; add some if necessary 
    var halves = cropped.split("."); //grab numbers to the right of the decimal 
    //compare digits in right half of string to digits wanted 
    var zerosNeeded = digits - halves[1].length; //number of zeros to add 
    for (var i=1; i <= zerosNeeded; i++) { 
     cropped += "0"; 
    } 
    return(cropped); 
} 
+0

......他們認真沒有什麼內置的?大聲笑? –