2008-10-21 10 views

Odpowiedz

11

Najlepsze, co masz z JavaScriptem, to funkcja FIXed() i ToPrecision() na swoich numerach.

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 

Waluta, przecinki i inne formaty będą musiały być wykonane przez Ciebie lub bibliotekę strony trzeciej.

0

Jeśli google javascript printf, znajdziesz wiele wdrożeń.

+0

z których wszystkie mają swoje wady. – holli

1

Ulepszony skrypt (poprzedni był wadliwy, przepraszam, szczerze mówiąc nie testowałem tego exaustively albo), to działa jak 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; 
} 
Powiązane problemy