2008-10-21 77 views

回答

11

JavaScript的最佳功能是對數字進行固定()和toPrecision()函數。

var num = 10; 
var result = num.toFixed(2); // result will equal 10.00 

num = 930.9805; 
result = num.toFixed(3); // result will equal 930.981 

num = 500.2349; 
result = num.toPrecision(4); // result will equal 500.2 

num = 5000.2349; 
result = num.toPrecision(4); // result will equal 5000 

num = 555.55; 
result = num.toPrecision(2); // result will equal 5.6e+2 

貨幣,逗號和其他格式必須由您或第三方庫完成。

0

如果谷歌的JavaScript的printf,你會發現很多的實現。

+0

所有這些都有自己的缺陷。 – holli 2008-10-21 14:45:40

1

改進腳本(以前是越野車,對不起,說實話我沒有測試過這exaustively其一),它的工作原理像PHP number_format:

function formatFloat(num,casasDec,sepDecimal,sepMilhar) { 
    if (num < 0) 
    { 
     num = -num; 
     sinal = -1; 
    } else 
     sinal = 1; 
    var resposta = ""; 
    var part = ""; 
    if (num != Math.floor(num)) // decimal values present 
    { 
     part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded) 
     while (part.length < casasDec) 
      part = '0'+part; 
     if (casasDec > 0) 
     { 
      resposta = sepDecimal+part; 
      num = Math.floor(num); 
     } else 
      num = Math.round(num); 
    } // end of decimal part 
    while (num > 0) // integer part 
    { 
     part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits 
     num = Math.floor(num/1000); 
     if (num > 0) 
      while (part.length < 3) // 123.023.123 if sepMilhar = '.' 
       part = '0'+part; // 023 
     resposta = part+resposta; 
     if (num > 0) 
      resposta = sepMilhar+resposta; 
    } 
    if (sinal < 0) 
     resposta = '-'+resposta; 
    return resposta; 
} 
相關問題