2008-10-21 49 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; 
} 
相关问题